Next.js Discord

Discord Forum

Zod error[0].message not working

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Brown bearOP
So I'm trying to use a useFormState to retrieve data back from my server action:-

const passwordSchema = z
  .string()
  .min(8, 'Password must be at least 8 characters long')

export const changePassword = async (state: any, formData: FormData) => {
  const newPassword = formData.get('newPassword') as string
  const result = passwordSchema.safeParse(newPassword)

  if (result.success) {
    return {
      success: true,
      data: result.data,
    }
  } else {
    return {
      success: false,
      error: result.error.message,
    }
  }
}


And in my client component:-

export default function PasswordChange() {
  const [state, formAction] = useFormState(changePassword, null)

  return (
    <form action={formAction}>
      <Label htmlFor="password" className="text-xl">
        Change password
      </Label>
      <p className="text-sm text-muted-foreground">
        Used to sign you into your account
      </p>
      <div className="mt-4 flex flex-col gap-2">
        <Input
          id="password"
          type="password"
          placeholder="Enter new password"
          name="newPassword"
          required
        />
        <ChangePasswordSubmitButton />
        <pre>
          {state?.error && (
            <div className="text-sm text-red-500">{state.error}</div>
          )}
        </pre>
      </div>
    </form>
  )
}


So in
 <pre>
          {state?.error && (
            <div className="text-sm text-red-500">{state.error}</div>
          )}
        </pre>


state.error shows up as :- https://i.imgur.com/Xiu1Frk.png, but state.error[0].message gives the error in typescript:- Property 'message' does not exist on type 'string'.ts(2339), and nothing displays.

I have to do
 {JSON.parse(state.error)[0].message}
for it to work. So why doesn't it work out of the box?

0 Replies