Next.js Discord

Discord Forum

Issue with useActionState and Server Action Response in Next.js

Unanswered
European hornet posted this in #help-forum
Open in Discord
European hornetOP
I’m working on a form in Next.js using server actions with the useActionState hook.
I have a signUp action that validates form data using Zod, and it’s expected to return an object containing success and errors.

Here’s my setup:
// Schema
const signUpSchema = z.object({
  first_name: z.string(),
  last_name: z.string(),
  username: z.string().min(4),
  dob: z.iso.date().min(formattedDate),
  phone_number: z.number().min(10),
  email: z.email(),
});

// Server action
export async function signUp(prevState, formData) {
  const result = signUpSchema.safeParse(Object.fromEntries(formData));

  if (!result.success) {
    const errors = z.flattenError(result.error);

    return {
      success: false,
      errors,
    };
  }

  // Handle Success
  return {
    success: true,
    errors: {},
  };
}

And here’s how I use it in my form:
const [state, signUpAction] = useActionState(signUp, undefined);

const Form = () => (
  <form action={signUpAction}>
    {/* form fields here */}
  </form>
);


⚠️ The Problem
On the client side, I get the following error when the form runs:
Uncaught Error: An unexpected response was received from the server.

It seems like the server action isn’t returning in the format that useActionState expects, but I can’t figure out what’s wrong since my return object looks fine.

Questions

1. Am I structuring the return value incorrectly for useActionState?

2. Does useActionState expect a very specific return shape?

3. How do I properly return errors alongside a success state from a server action?

Any insights or examples would be greatly appreciated 🙏

1 Reply

Asian black bear
At first glance everything looks plausible. You should verify the output in the console of the server to see if it indicates some error. Also, just for debugging purposes, do not return an error object in the error case and see if the result of flattenError is somehow causing issues.

Answering your questions:
1. No.
2. No.
3. Just like that.