React and Flux: "dispatch in the middle of a dispatch" to show error message from an API call

Viewed 1543

Im using Flux, React and I have the components Simple and Messages:

  • Simple: it'is a simple component that calls an API by an Action. The Action do a ajax request and dispatch the result in jqXHR.done(). Simple have a change listener to wait the dispatch of the result. If the result is null, I would like to show an error using my Messages component, so I call my MessagesAction.addError('My result is null').
  • Messages: a component that show errors for the application. This component have a change listener waiting for new messages to display. It's placed in the header of my application.

The problem occur when I receive the null result and immediately calls the MessagesAction.addError inside the Simple component. In fact, I know that this can result in "Dispatch in the middle of a dispatch" error, but I don't know how refactor this code to show the error message using Flux.

Disclaimer 1: I can't use setTimeout function to resolve this problem. This is not the right solution.

Disclaimer 2: The Simple component represents any other component from app that will be show a message using the Messages component too.

Simple code:

findUser: function (value) {
  UserAction.find(value);
},

componentDidMount: function () {
  UserStore.addChangeListener(this.updateUser);
},

updateUser: function(){
  var user = UserStore.getUser();
  if (user == null){
     MessagesAction.addError('My result is null!'); //here occur the error!
  } else {
     //set my user with setState
  }
},

Messages code:

componentDidMount: function () {
    MessagesStore.addChangeListener(this.addMessage);
},

addMessage: function () {
    this.setState({
        messages: MensagensStore.getMessages()
    });
},

Thanks!

2 Answers
Related