Next.js Discord

Discord Forum

NextJS's replacement for SvelteKit load functions

Unanswered
Little fire ant posted this in #help-forum
Open in Discord
Avatar
Little fire antOP
Hello,

I'm porting a small SvelteKit project into Next.JS to learn more about it. I have a component that simply lists some items from a database and has a create form and delete buttons for each item in the list.

In SvelteKit, the +page.server.ts load function returns an {items} object. The create and delete buttons use form actions. I'm leveraging SvelteKit's default behavior for form actions of automatically reloading the current page's load after form actions is evaluated on the server, as part of that form action's response payload.

The Next.JS documentation recommends using React's new experimental server actions for this kind of thing.
The docs specify that: (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations)
Server Actions integrate with the Next.js caching and revalidation architecture. When an action is invoked, Next.js can return both the updated UI and new data in a single server roundtrip.

I need to use a server action rather than an client action, since the action needs to perform a server-side async/await database call.

I currently load {items} using an await database call in a server-side component, then pass those down as props to a client-side component where they're set as state. The client-side form action handlers each set that state after the server action completes. This approach requires each server action to return {items} and each client-side action handler to set the state though.

Does Next.JS have something like SvelteKit's server load function that can pass reloadable server-provided state to a client-side component, or am I better off writing an API endpoint to fetch this data from a client-side component?

1 Reply

Avatar
Little fire antOP
Here are a few ways I thought of to do this. Is one of these alternatives a best practice?
1. [current] Load the data in a server-side component. Pass it to a client-side component as a prop. Set state based on that prop. Modify each server action to also return that state. Manually update the state in each client-side form action handler.
2. Get Next.JS to reload the route somehow, instead of using setState. I tried router.refresh() but that didn't do the trick. I understand that server component aren't hydrated and intrinsically have no reactivity once rendered, hence their lack of support for hooks like useState
3. Add an API handler for this page's data. Call that using fetch from a client-side component. Modify each form handler that mutates it to fetch it and replace the component's state for this data.
4. #3 + swr or react-query instead of NextJS's fetch
5. Move {items} state into MobX or similar.