#How to handle the return value of a server action?
1 messages · Page 1 of 1 (latest)
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.