#How to handle the return value of a server action?

1 messages · Page 1 of 1 (latest)

opaque shore
#

I have a form for signing out the user which invokes a server action. The server action returns true or false, how can I handle the response of a server action back in my client component?

sharp violetBOT
#

Hi @opaque shore. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To handle the return value of a server action in your client component, you can use a React hook like useFormState. This hook allows you to receive the return value of your server action and use it in your client component.

Here's an example of how you can use it:

'use client'
 
import { useFormState } from 'react-dom'
import { signOutUser } from '@/app/actions' // replace with your sign out action
 
const initialState = {
  message: '',
}
 
export function SignOut() {
  const [state, formAction] = useFormState(signOutUser, initialState)
 
  return (
    <form action={formAction}>
      {/* ... */}
      <p aria-live="polite" className="sr-only">
        {state?.message} // handle the return value here
      </p>
    </form>
  )
}

In this example, useFormState is used to handle the return value of the signOutUser server action. The state variable will contain the return value of your server action, which you can then use in your client component.

Please note that useFormState is a React hook and therefore must be used in a Client Component. Also, by passing the action to useFormState, the action's function signature changes to receive a new prevState or initialState parameter as its first argument.

For more information, you can refer to the Next.js documentation on server-side validation and error handling (https://nextjs.org/docs/app/building-your-application/data-fetching/server-actions-and-mutations#server-side-validation-and-error-handling).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: