Answer the question
In order to leave comments, you need to log in
What is wrong here in the code that the modal window does not appear (another question)?
I am doing registration in my app. When I submit a form to my local server and this server already has a user with this username, it returns a 400 error and response:
[{
"message": "User with this username already exists",
"field": "username",
"validation": "unique"
}]
if(Array.isArray(res)){
const err = res[0].message;
alert(err);
} else {
if(Array.isArray(res)){
const err = res[0].message;
return (<div className="err-response">{err}</div>);
.err-response{
width: 1000px;
height: 500px;
background: grey;
}
const SignupForm = () => {
const {handleSubmit, values, handleChange, errors, handleBlur} = useFormik({
/......
onSubmit: async (formValues) => {
setSubmitting(true);
try {
const res = await api('api/auth/register', {
method:'POST',
body: JSON.stringify(formValues)
});
if(Array.isArray(res)){ //this
const err = res[0].message; //this
alert(err); //this
} else {
/......
}
} catch(e) {
console.error(e);
}
},
});
return (
<div className="form">
<form onSubmit={handleSubmit}>
/............
<button type="submit" disabled={isSubmitting}>Submit Form</button>
</form>
</div>
);
};
Answer the question
In order to leave comments, you need to log in
The fact is that
onSubmit: async (formValues) => {
try {
const res = await .........
if(Array.isArray(res)){
const err = res[0].message;
return (<div className="err-response">{err}</div>);
// ^ это не return из реакт-компонента, а из функции обработчика сабмита формы
// рендериться ничего не будет
}
},
const SignupForm = () => {
const [errorMessage, setErrorMessage] = React.useState(null)
....
if(Array.isArray(res)){
// то есть ошибка это когда res - массив?
setErrorMessage (res[0].message)
// теперь в errorMessage у нас текст ошибки, а не null
}
....
return (
<div className="form">
{ errorMessage && <p>${errorMessage}</p> }
{/* ^ если там null, то ничего не будет писаться */}
.....
</div>
)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question