I am trying to get my nextjs app to refresh routes after a form submits, so that i can update data on the page, without refreshing the browser.
I have these server actions:
'use server';
import { createServerSupabaseClient } from '../lib/serverSupabaseClient';
import { auth } from '@clerk/nextjs/server';
import { revalidatePath } from 'next/cache';
export async function fetchJudgments() {
const { userId } = auth();
if (!userId) throw new Error('Unauthorized');
const supabase = await createServerSupabaseClient();
const { data, error } = await supabase.from('judgment').select('*');
if (error) throw error;
revalidatePath(`/judgments/${judgmentId}`);
return data;
}
export async function fetchNotes(judgmentId: number) {
const { userId } = auth();
if (!userId) throw new Error('Unauthorized');
const supabase = await createServerSupabaseClient();
const { data, error } = await supabase
.from('note')
.select('*')
.eq('judgment_id', judgmentId)
.order('start_index', { ascending: true });
if (error) throw error;
return data;
}
export async function addNote(
comment: string,
start_index: number,
end_index: number,
judgment_id: number
) {
const { userId } = auth();
if (!userId) throw new Error('Unauthorized');
const supabase = await createServerSupabaseClient();
const { error } = await supabase
.from('note')
.insert({ comment, start_index, end_index, judgment_id, user_id: userId });
if (error) throw error;
revalidatePath(`/judgments/${judgment_id}`);
const updatedNotes = await fetchNotes(judgment_id);
return updatedNotes; // Return the updated notes
}
export async function editNote(
id: number,
comment: string,
judgment_id: number
) {
const { userId } = auth();
if (!userId) throw new Error('Unauthorized');
const supabase = await createServerSupabaseClient();
const { error } = await supabase
.from('note')
.update({ comment })
.eq('id', id)
.eq('user_id', userId);
if (error) throw error;
revalidatePath(`/judgments/${judgment_id}`);
const updatedNotes = await fetchNotes(judgment_id);
return updatedNotes; // Return the updated notes
}
export async function deleteNote(
id: number,
judgment_id: number
) {
const { userId } = auth();
if (!userId) throw new Error('Unauthorized');
const supabase = await createServerSupabaseClient();
const { error } = await supabase
.from('note')
.delete()
.eq('id', id)
.eq('user_id', userId);
if (error) throw error;
revalidatePath(`/judgments/${judgment_id}`);
const updatedNotes = await fetchNotes(judgment_id);
return updatedNotes; // Return the updated notes
}
and I have this in my client component:
'use client';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useUser } from '@clerk/nextjs';
import { useRouter } from 'next/navigation';
import { Dialog } from '@headlessui/react';
import Loading from "../loadingSpinner";
import { Note, Judgment, SelectedTextType } from '../../../types';
import { fetchJudgments, fetchNotes, addNote, editNote, deleteNote } from '../../actions';
export default function JudgmentBody() {
const { user } = useUser();
const router = useRouter();
const [judgments, setJudgments] = useState<Judgment[]>([]);
const [selectedJudgment, setSelectedJudgment] = useState<Judgment | null>(null);
const [notes, setNotes] = useState<Note[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [selectedText, setSelectedText] = useState<SelectedTextType | null>(null);
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false);
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [editingNote, setEditingNote] = useState<Note | null>(null);
const [deletingNoteId, setDeletingNoteId] = useState<number | null>(null);
const [newNoteComment, setNewNoteComment] = useState('');
const judgmentRef = useRef<HTMLDivElement>(null);
const [isAddingNote, setIsAddingNote] = useState(false);
const [isEditingNote, setIsEditingNote] = useState(false);
const loadNotes = useCallback(async (judgmentId: number) => {
setLoading(true);
try {
const data = await fetchNotes(judgmentId);
setNotes(data);
} catch (error) {
console.error("Error loading notes:", error);
setError('Failed to fetch notes');
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
async function loadJudgments() {
setLoading(true);
try {
const data = await fetchJudgments();
setJudgments(data);
} catch (error) {
console.error("Error loading judgments:", error);
setError('Failed to fetch judgments');
} finally {
setLoading(false);
}
}
if (user) {
loadJudgments();
}
}, [user]);
useEffect(() => {
if (selectedJudgment) {
loadNotes(selectedJudgment.id);
}
}, [selectedJudgment, loadNotes]);
const handleAddNote = async (): Promise<void> => {
if (selectedText && selectedJudgment) {
setIsAddingNote(true);
try {
const updatedNotes = await addNote(newNoteComment, selectedText.start, selectedText.end, selectedJudgment.id);
setNotes(updatedNotes);
await router.refresh();
} catch (error) {
console.error("Error adding note:", error);
setError('Failed to add note');
} finally {
setIsAddingNote(false);
setIsAddDialogOpen(false);
setNewNoteComment('');
setSelectedText(null);
}
}
};
const handleEditNote = async (): Promise<void> => {
if (editingNote && selectedJudgment) {
setIsEditingNote(true);
try {
const updatedNotes = await editNote(editingNote.id, newNoteComment, selectedJudgment.id);
setNotes(updatedNotes);
await router.refresh();
} catch (error) {
console.error("Error editing note:", error);
setError('Failed to edit note');
} finally {
setIsEditingNote(false);
setIsEditDialogOpen(false);
setEditingNote(null);
setNewNoteComment('');
}
}
};
const handleDeleteNote = async (): Promise<void> => {
if (deletingNoteId !== null && selectedJudgment) {
try {
// Optimistic update
setNotes(prevNotes => prevNotes.filter(note => note.id !== deletingNoteId));
await deleteNote(deletingNoteId, selectedJudgment.id);
await loadNotes(selectedJudgment.id);
router.refresh();
} catch (error) {
console.error("Error deleting note:", error);
setError('Failed to delete note');
// Revert optimistic update
await loadNotes(selectedJudgment.id);
} finally {
setIsDeleteDialogOpen(false);
setDeletingNoteId(null);
}
}
};
const handleTextSelection = () => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
const judgmentRect = judgmentRef.current?.getBoundingClientRect();
const start = parseInt(range.startContainer.parentElement?.id.split('-')[1] || '0', 10);
const end = parseInt(range.endContainer.parentElement?.id.split('-')[1] || '0', 10);
setSelectedText({
text: selection.toString(),
start,
end,
top: judgmentRect ? rect.top - judgmentRect.top : 0,
left: rect.left,
});
setIsAddDialogOpen(true);
}
};
const splitIntoParagraphs = (text: string) => {
let globalSentenceIndex = 0;
return text
.split(/ns*n/)
.filter((paragraph) => paragraph.trim() !== '')
.map((paragraph) => {
const sentences = paragraph.split('. ').map((sentence) => {
const trimmedSentence = sentence.trim();
return {
text: trimmedSentence,
index: globalSentenceIndex++,
};
});
return { text: paragraph, sentences };
});
};
useEffect(() => {
if (notes.length > 0 && selectedJudgment) {
const judgmentElement = judgmentRef.current;
if (judgmentElement) {
const judgmentRect = judgmentElement.getBoundingClientRect();
const updatedNotes = notes.map((note) => {
const startElement = document.getElementById(`sent-${note.start_index}`);
if (startElement) {
const rect = startElement.getBoundingClientRect();
const top = rect.top - judgmentRect.top;
return { ...note, top };
}
return note;
});
setNotes(updatedNotes);
}
}
}, [notes, selectedJudgment]);
if (!user) {
return <div>Please sign in to access this page.</div>;
}
return (
<div className="container mx-auto p-4">
{loading && <Loading />}
{error && <div className="error bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">{error}</div>}
<select
className="block w-full p-2 mb-4 border rounded"
onChange={(e) => {
const judgment = judgments.find((j) => j.id === Number(e.target.value));
setSelectedJudgment(judgment || null);
}}
>
<option value="">Select a judgment</option>
{judgments.map((judgment) => (
<option key={judgment.id} value={judgment.id}>
{judgment.title}
</option>
))}
</select>
<div className="grid grid-cols-3 gap-4">
<div className="col-span-2">
<div id="judgment" ref={judgmentRef} className="relative pr-4" onMouseUp={handleTextSelection}>
{selectedJudgment && splitIntoParagraphs(selectedJudgment.decision).map((paragraph, pIndex) => (
<p key={pIndex} className="mb-4 leading-loose">
{paragraph.sentences.map((sentence, sIndex) => (
<span key={sIndex} id={`sent-${sentence.index}`} className="sentence">
{sentence.text}.
</span>
))}
</p>
))}
</div>
</div>
<div className="relative">
{notes.map((note) => (
<div key={note.id} className="absolute left-0 right-0" style={{ top: `${note.top}px` }}>
<div className="mb-4 p-2 bg-yellow-100 rounded">
<p>{note.comment}</p>
<div className="mt-2">
<button onClick={() => { setEditingNote(note); setNewNoteComment(note.comment); setIsEditDialogOpen(true); }} className="mr-2 text-blue-500">Edit</button>
<button onClick={() => { setDeletingNoteId(note.id); setIsDeleteDialogOpen(true); }} className="text-red-500">Delete</button>
</div>
</div>
</div>
))}
</div>
</div>
<Dialog open={isAddDialogOpen} onClose={() => setIsAddDialogOpen(false)} as="div" className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-center justify-center min-h-screen">
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
Add Note
</Dialog.Title>
<div className="mt-2">
<textarea
value={newNoteComment}
onChange={(e) => setNewNoteComment(e.target.value)}
className="w-full p-2 border rounded mb-4"
rows={4}
/>
</div>
<div className="mt-4 flex justify-end">
<button
type="button"
className="mr-2 inline-flex justify-center rounded-md border border-transparent bg-gray-100 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-500 focus-visible:ring-offset-2"
onClick={() => setIsAddDialogOpen(false)}
disabled={isAddingNote}
>
Cancel
</button>
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
onClick={handleAddNote}
disabled={isAddingNote}
>
{isAddingNote ? 'Adding...' : 'Add'}
</button>
</div>
</Dialog.Panel>
</div>
</Dialog>
<Dialog open={isEditDialogOpen} onClose={() => setIsEditDialogOpen(false)} as="div" className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-center justify-center min-h-screen">
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
Edit Note
</Dialog.Title>
<div className="mt-2">
<textarea
value={newNoteComment}
onChange={(e) => setNewNoteComment(e.target.value)}
className="w-full p-2 border rounded mb-4"
rows={4}
/>
</div>
<div className="mt-4 flex justify-end">
<button
type="button"
className="mr-2 inline-flex justify-center rounded-md border border-transparent bg-gray-100 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-500 focus-visible:ring-offset-2"
onClick={() => setIsEditDialogOpen(false)}
disabled={isEditingNote}
>
Cancel
</button>
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-blue-100 px-4 py-2 text-sm font-medium text-blue-900 hover:bg-blue-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"
onClick={handleEditNote}
disabled={isEditingNote}
>
{isEditingNote ? 'Saving...' : 'Save'}
</button>
</div>
</Dialog.Panel>
</div>
</Dialog>
<Dialog open={isDeleteDialogOpen} onClose={() => setIsDeleteDialogOpen(false)} as="div" className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-center justify-center min-h-screen">
<Dialog.Panel className="w-full max-w-md transform overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all">
<Dialog.Title as="h3" className="text-lg font-medium leading-6 text-gray-900">
Delete Note
</Dialog.Title>
<div className="mt-2">
<p className="text-sm text-gray-500">
Are you sure you want to delete this note? This action cannot be undone.
</p>
</div>
<div className="mt-4 flex justify-end">
<button
type="button"
className="mr-2 inline-flex justify-center rounded-md border border-transparent bg-gray-100 px-4 py-2 text-sm font-medium text-gray-900 hover:bg-gray-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-gray-500 focus-visible:ring-offset-2"
onClick={() => setIsDeleteDialogOpen(false)}
>
Cancel
</button>
<button
type="button"
className="inline-flex justify-center rounded-md border border-transparent bg-red-100 px-4 py-2 text-sm font-medium text-red-900 hover:bg-red-200 focus:outline-none focus-visible:ring-2 focus-visible:ring-red-500 focus-visible:ring-offset-2"
onClick={handleDeleteNote}
>
Delete
</button>
</div>
</Dialog.Panel>
</div>
</Dialog>
</div>
);
}
When I submit the forms, the data is going to supabase, and I cannot find a way to make the note.comment add or edit actions update on the page without refreshing the browser. I have tried multiple combinations of revalidatePath in the server actions and refresh.router() in the client functions. I have added optimistic loading as well as a time out to try and figure out why i can’t get this data to load.
does anyone know how to get components to udpate in app router? I’ve tried adding the setState update, awaiting the router.refresh and revalidating paths in all actions. I still cant find a way to refresh the notes (which belong to judgments) on the judgment page, when the form actions are completed.
1