formsnext.jscallbackserver-action

Callback functions with server actions


I am just getting myself familiar with server actions in Next.js 14 app router, server actions are generally used to make post requests to the server ... Is there a way server actions can trigger a function on the client, the idea is to have something similar to React query onSucess and onError, those functions can be triggered based on the state the response to an API, let's assume a user makes a sign up request using server actions with an already existing email, and in my application functionality I need to trigger a toast notification to let the user know the email is already in use, any idea how to implement this...

This is a snippet in Next.js docs how we can use useFormState to get a return value from the server action, this can be reworked with a useEffect to trigger a function on the client, but i really do no want a useEffect solution.

export function AddForm() {
const [state, formAction] = useFormState(createTodo, initialState)
    return (
        <form action={formAction}>
            <label htmlFor="todo">Enter Task</label>
            <input type="text" id="todo" name="todo" required />
            <SubmitButton />
            <p aria-live="polite" className="sr-only">
              {state?.message}
            </p>
        </form>
    )
}

I can confirm useFormStatus with useEffect works but I am hoping for a more optimized solution.


Solution

  • I'm not sure if this is a more optimized solution, but it's different. You could use useTransition. In this example, signUp is a server action. Within the handleSignup function, you can set states or parse result to trigger toasts and so on.

    import { useTransition } from "react";
    
    const [isPending, startTransition] = useTransition();
    
    const handleSignup = form.handleSubmit(async (data) => {
        startTransition(async () => {
            const result = await signUp(data);
        });
    });
    
    return (
        <Form {...form}>
            <form onSubmit={handleCreateProspect}>
    ...