I have a Next.js 14 app where I am listing data from my DB on a page with useSWR. The data is updated via a server action called by submission of a form on a modal that is opened with the Next.js 14 parallel route intercept pattern from the page that displays the data. (Think list of notes on a page, with an "+ Add Note" button that redirects to a route that is intercepted, opening a modal).
I am relatively new to using useSWR, and I am curious on the best practice for listing data using useSWR in one spot, and mutating that data in another spot.
In order to revalidate the data on the page once the form on the modal is submitted, I am calling useSWR in two places:
- On the page where I am listing the data to get the data itself:
const {
data,
error: isError,
isLoading,
mutate: refreshProjectNotes,
} = useSWR(['/api/getProjects', projectId], () =>
fetchProjectNotes(projectId),
)
Returned from component:
{data.notes.length > 0 ? (
data.notes.map((note: any) => (
<div>{note.title}</div>
)
)) : (
<p>No notes found</p>
)}
- On the page where I am updating the data to be displayed in the notes list, purely to "grab" the mutate function which can be called once my call to the server action that updates the data with the form is successful:
const { mutate: refreshProjectNotes } = useSWR([
'/api/getProjects',
projectId,
])
Is this typical for useSWR usage, or should I somehow be exporting and grabbing that refreshProjectNotes function from the first component that lists the data, so that I am not duplicating a useSWR call to the same route handler?
my approach is typically to use the SWR React Hook inside a custom React Hook for an API endpoint. The custom React Hook by default calls an endpoint via SWR. In addition I add any related API operations as functions. The custom React Hook is utilized where needed inside the App.