Ad

ReactJS - Waiting For Action To Finish Within ComponentDidMount

- 1 answer

Code in question is below. I have an async UserActions call within componentDidMount, and immediately afterwards I am looking to user information from within the UserStore populated by this action. Clearly, I cannot rely upon UserStore.isLargeAccess() being defined. Is the best convention to place the code relying on the action within a callback, or am I missing some bigger design choice?

componentDidMount() {
    this.changeListener = this._onChange.bind(this);
    UserStore.addChangeListener(this.changeListener);
    OrganizationStore.addChangeListener(this.changeListener);

    // Fetch user info
    UserActions.get(AuthStore.username);

    // UserStore.isLargeAccess() is undefined here,
    // because the previous action has not finished.
    if (UserStore.isLargeAccess()) {
      OrganizationActions.getUsers(this.state.organization);
    }

    if (UserStore.isGlobalAccess()) {
      OrganizationActions.getOrganizations();
    }
  }
Ad

Answer

How it should to work (If I understand your flow):

  1. You should register different callbacks for each of your stores (otherwise you don't know which store emit event)
  2. You start some async work.
  3. When async work is finished then it dispatch action with some data from async work
  4. your stores UserStore and OrganizationStore listens for this action, and when they receive it, they do some job and emit change.
  5. When they emit change, then they call callbacks from your component. In each callback you know which store invoke it, And therefore you know from what store get data.
Ad
source: stackoverflow.com
Ad