Next.js Discord

Discord Forum

Asking for edit/update data example

Unanswered
Spectacled bear posted this in #help-forum
Open in Discord
Spectacled bearOP
I'm new to next and currently developing a simple CRUD web application. I'm reaching a point where I need to create and update (updating is the most important) the data, and I'm not sure exactly how to do it. Can anyone provide an example of best practices for doing this, especially on how to handle the form? I've googled and found nothing useful. Any repos or articles would be appreciated

5 Replies

Try Server Actions

You can directly pass the function to an “action” prop in the form: <form action = {yourAction}>

This will handle the form data directly to your server action.

You could also call them inside your typical onSubmit/onClick handlers like a regular function, with the difference this will run exclusively on the server.
You work with the input itself not react state, you can use a hook to handle return values from submitting the action, in case you want to get errors back or whatever.

const [state, formAction, isPending] = useActionState(yourActionFn, initialState);
// initial state fills the "state" variable for the initial render
You can do form submissions via the action prop purely on the server side too, when the action comlpetes the form cleans up the fields by default, but it doesn't make much sense to work with a form purely in the server, most of the times forms are client components.

Server Actions are ultimately a function that runs on the server, you can conmbine them with any other solutions such as React Hook Form, and calling the serverActionFn inside the regular onSubmit fn