I’m trying to do error handling in Next.js. I’m using a server action that is passed to a form and invoked when the form is submitted, like this (according to documentation):
Form Component
'use client'
import { useFormState } from 'react-dom'
import { createUser } from '@/app/actions'
const initialState = {
message: '',
}
export function Signup() {
const [state, formAction] = useFormState(createUser, initialState)
return (
<form action={formAction}>
<label htmlFor="email">Email</label>
<input type="text" id="email" name="email" required />
{/* ... */}
<p aria-live="polite" className="sr-only">
{state?.message}
</p>
<button>Sign up</button>
</form>
)
}
Server Action
'use server'
export async function createUser(prevState: any, formData: FormData) {
// ...
return {
message: 'Please enter a valid email',
}
}
I know this is the just the last part of the action, but it’s the important part
the issue is when I tried to implement this the server action didn’t return the response object, i.e. the state
remains undefined
I even tried a bare bones implementation of this without the useFormState
:
Form Component
'use client'
import { useFormState } from 'react-dom'
import { createUser } from '@/app/actions'
export function Signup() {
const [error, setError] = useState<string>()
return (
<form action={async (data) => {
const res = await createUser(data)
if (res?.message) {
setError(res.message)
}
}}>
<label htmlFor="email">Email</label>
<input type="text" id="email" name="email" required />
{/* ... */}
<p aria-live="polite" className="sr-only">
{error}
</p>
<button>Sign up</button>
</form>
)
}
yet the server action returns undefined
, I also checked the the server action is actually invoked and it is invoked.
Please, someone provide a solution to this
Note: I know that useFormState
is gonna be replaced by useActionState
, I tried it and it’s still returning undefined