Reputation: 895
I have this form code below:
submitForm = (e) => {
e.preventDefault();
const { user } = this.state;
const { dispatch } = this.props;
if (user.firstName && user.lastName && user.userName && user.password) {
this.props.dispatch(userActions.register(user));
} else {
this.setState({
error: "Form Incomplete"
})
}
if(this.state.error === "") {
this.props.history.push("/login");
}
}
The problem is this.props.dispatch is an async call. It gets fired when a user successfully fills out the form field.
The problem is it can fail if the username already exists and it will populate the error state. If this occurs my app keeps going and hits this.props.history and redirects the user even if the form has an error.
How do I basically say "Wait until this.props.dispatch is complete and then check to see if there are any errors. If not then redirect"?
Upvotes: 1
Views: 284
Reputation: 109
I imagine that you are sending this data to a backend of some sort. Just add a bool to the server response to let your front end know what to do next.
submitForm = (e) => {
e.preventDefault();
const { user } = this.state;
const { dispatch } = this.props;
if (!( user.password && user.lastName &&user.userName && user.firstName )) {
this.props.dispatch(userActions.register(user));
} else {
this.setState({
error: "Form Incomplete"
})
}
if(isValid) {
this.props.history.push("/login");
}
}
Upvotes: 1
Reputation: 936
You can specify submitForm
as an async
function like this:
submitForm = async (e) => {
and then add the await
keyword before this.props.dispatch
await this.props.dispatch(userActions.register(user));
But since you are using redux, and I am assuming something like redux-promise-middleware, then you should let that handle the success/failure of your async calls.
You mentioned that onInit the form continuously redirects because there is no error set. Can we change the initial error value to false
and if error is ever true
then re-direct the user? And then, the only time you would ever set error
to true
would be when an actual error came from your call.
Upvotes: 3