0

I don't know how can I easy resolve the problem. I have a form that user can fill and send stuff to my database. Form has his own state for it (here for example is just username). I don't know how to call setState (to give message to user about result) after dispatching redux action. Function postDataBegin is simple and shows spinner only. I think there is a problem, cause this function is synchronous (tell me if not). How can i fix it? What should i learn?

submitForm = e => {
  e.preventDefault();
  const { username } = this.state;
  if (!question) {
    this.setState({ messageToUser: "Fill the form" });
  } else {
    // onSubmit is redux action from props
    this.props.onSubmit(username);
    //HOW TO CALL THIS FUNCTION AFTER FUNC ABOVE?
    this.setState({ messageToUser: "Send" });
  }
};

<Form type="submit" onSubmit={this.submitForm}/>

export const postUserQuestion = username => dispatch => {
  dispatch(postDataBegin());
  return post(postUsernameAPI, username)
    .then(res => dispatch(postUsernameAPISucceeded(res)))
    .catch(error => dispatch(postUsernameAPIFailure(error)));
};
2
  • Hi, you must learn reducer. After dispatch reducer called, then reducer update or set new state, and you can use this state with store. Commented Aug 18, 2019 at 14:22
  • Ye i know about it but i don't want to use reducer store only for simple message - my form is stateful component already. There is no other way? The problem is that my message in Form component shows immediately after I click on submit button - i want make it to wait. Commented Aug 18, 2019 at 14:33

1 Answer 1

1

Your action returns a promise, so you can use then method on it to provide a callback:

submitForm = e => {
  e.preventDefault();
  const { username } = this.state;
  if (!question) {
    this.setState({ messageToUser: "Fill the form" });
  } else {
    // onSubmit is redux action from props
    this.props.onSubmit(username).then(() => {
      this.setState({ messageToUser: "Send" });
    });
  }
};

Altho it'd probably be better to store that data on reducer as well, and change it the same time when the form is submitted.

Sign up to request clarification or add additional context in comments.

1 Comment

Great! I knew it is all about the Promise. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.