I'm having troubles with React-Final-Form library. From the onSubmit
function, I return a validation error, but it is not displayed on the form itself. Here you can see my code:
My form:
<Form
onSubmit={this.onSubmit}
initialValues={{}}
validate={
values => {
const errors = {}
if (!values.username) {
errors.username = "This field is required"
}
if (!values.password) {
errors.password = "This field is required"
}
return errors
}
}
render={({submitError, handleSubmit, submitting, values}) => (
<form onSubmit={handleSubmit}>
<div className="form-group">
<label>First Name</label>
<Field name="username">
{({input, meta}) => (
<>
<input {...input} type="text" placeholder="Username"
className={"form-control" + ((meta.error || meta.submitError) && meta.touched ? " is-invalid" : "")}/>
{(meta.error || meta.submitError) && meta.touched ?
<div
className="invalid-feedback">{meta.error || meta.submitError}</div> : null
}
</>
)}
</Field>
{submitError && (
<div>{submitError}</div>
)}
</div>
<div className="form-group">
<label>Password</label>
<Field name="password">
{({input, meta}) => (
<>
<input {...input} type="password"
placeholder="Password"
className={"form-control" + ((meta.error || meta.submitError) && meta.touched ? " is-invalid" : "")}/>
{(meta.error || meta.submitError) && meta.touched ?
<div
className="invalid-feedback">{meta.error || meta.submitError}</div> : null
}
</>
)}
</Field>
</div>
<button type="submit" disabled={submitting}
className="btn btn-block btn-outline-secondary">Log In
</button>
<pre>{JSON.stringify(values, 0, 2)}</pre>
</form>
)}
/>
My onSubmit function:
onSubmit = async values => {
const errors = {}
let loginData = {
username: values.username,
password: values.password
}
usersAPI.getCSRF().then((response) => {
usersAPI.login(loginData)
.then(response => {
if (response.data.login_status === "Incorrect data") {
console.log("Invalid data")
errors.username = "Invalid login or password"
errors.password = "Invalid login or password"
return errors
} else {
localStorage.setItem('token', response.data.token)
this.props.setAuthState(true)
console.log("Logged in successfully")
}
})
.catch(err => console.log(err))
})
}
The problem is in axios request. If my back-end server sends the response that credentials are invalid, then console.log("Invalid data")
will appear in console but nothing will happen with form. If I comment my axios request and just leave this code:
onSubmit = async values => {
return {username: "Invalid data"}
}
So, in this case everything works correct. Who can tell me How can I optimize my axios request so after that my form will get submission errors that returned from
errors.username = "Invalid login or password"
errors.password = "Invalid login or password"
return errors
question from:
https://stackoverflow.com/questions/65869015/submission-error-is-not-shown-on-react-final-form 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…