I have a Next.js app that makes an API call for a register form. When there are server side validation errors I get a response back like this:
{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."],"password":["The password must be at least 8 characters."]}}
In my code I would like to show the email
and password
errors to the user if they are present. Currently my code is:
const RegisterPage: NextPageWithLayout = () => {
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [setEmailError, emailError] = useState<string | null>(null)
const [setPasswordError, passwordError] = useState<string | null>(null)
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
if (isSubmitting) return;
setIsSubmitting(true);
try {
// handle success
} catch (err){
// @ts-ignore
const errors = err?.response?.data?.errors;
if(errors instanceof Object){
setEmailError(errors['email']) // this does not work
setPasswordError(errors['password'] || null) // this does not work
}
setIsSubmitting(false);
}
};
However this code does not work. My IDE shows a couple errors on the line for setting email and password errors:
TS2349: This expression is not callable.
Type 'String' has no call signatures.
TS2721: Cannot invoke an object which is possibly 'null'.
How can I set the emailError
and passwordError
variables so I can display the error messages to the user if they are present?
CodePudding user response:
in useState
, Setter method is the second argument not the first.
const [emailError, setEmailError ] = useState<string | null>(null)
const [passwordError, setPasswordError] = useState<string | null>(null)
add a type to errors and check if error is null or not
const errors: {email?: string, password?: string} = err?.response?.data?.errors;
if(errors){
setEmailError(errors?.email || null)
setPasswordError(errors?.password || null)
}