Answer the question
In order to leave comments, you need to log in
How to display message not in alert but in modal window?
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 {
const SignupForm = () => {
const history = useHistory();
const {handleSubmit, values, handleChange, errors, handleBlur, isSubmitting, setSubmitting} = useFormik({
initialValues: {
username: '',
/..........
},
validateOnBlur: false,
validateOnchange: false,
validationSchema: yup.object().shape({
username: yup.string()
.required('This field is required'),
/.............
}),
onSubmit: async (formValues) => {
setSubmitting(true);
try {
const res = await api('api/auth/register', {
method:'POST',
body: JSON.stringify(formValues)
});
if(Array.isArray(res)){ // проверка
const err = res[0].message;
alert(err);
} else {
const token = res.token.token;
localStorage.setItem('myToken', token);
console.log('Result!',token);
history.push("/home");
}
} catch(e) {
console.error(e);
} finally {
setSubmitting(false);
}
},
});
return (
<div className="form">
<form onSubmit={handleSubmit}>
<SignupInput
label="username"
id="username"
inputProps={{
name:'username',
value: values.username,
onChange: handleChange,
onBlur: handleBlur,
disabled: isSubmitting,
}}
error={errors.username}
/>
/............
<div className="form-button">
<button type="submit" disabled={isSubmitting}>Submit Form</button>
</div>
</form>
</div>
);
};
const SignupInput = ({
label, inputProps, error, id,
}) => (
<div className="ffinput">
<label htmlFor={id} className="ffinput-label">
{label}
</label>
<input {...inputProps} id={id} />
{error && <span className="ffinput-error">{error}</span>}
</div>
);
</spoiler>
SignupInput.propTypes = {
label: PropTypes.string.isRequired,
inputProps: PropTypes.instanceOf(Object).isRequired,
error: PropTypes.string,
id: PropTypes.string.isRequired,
};
SignupInput.defaultProps = {
error: '',
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question