Search code examples
fluxstate-management

Different ways to call dispatch in Alt.js?


I have seen three different patterns for this and the alt docs do not make the distinction clear. If I have an action, how should I go about calling dispatch? Here are the three ways I have seen:

1. The action returns a function, which `dispatch` is passed into.

  addPayment(args) {
    return (dispatch) => {
      dispatch();
      // other action code
    };
  }

2. The action calls this.dispatch.

  addPayment(args) {
    this.dispatch();
    // other action code
  }

3. The action does not call dispatch.

  addPayment(args) {
    // other action code
  }

It is not clear to me what difference there is between these three options, and it is especially unclear to me whether option #3 calls dispatch at all.

The bindActions method seems to associate actions with action handlers, so it would kind of make sense that a given action handler should be called automatically when the associated action is called, which would result in code that looked like option #3. But then, why would we ever need to explicitly call dispatch?

There is no tag for alt, so....yeah. Tagging it flux since that's the closest match.


Solution

  • Okay, as I understand things, approach #2 was patched out in later releases of alt and will now cause an error.

    Approach #1 works fine when you want to trigger dispatch before your action completes. It's generally used when you have a handler that initiates a loading state in the UI, so you want to set things to loading while your action completes. Then you have separate success/failure actions (often just generated via alt's generateActions) with their own handlers which take care of what happens after the action completes.

    Approach #3 is for when you want to trigger dispatch after your action completes. Here's a key bit from the alt docs that I missed:

    You can also simply return a value from an action to dispatch.

    So simply returning a value will call dispatch, and thus your action completes first. The docs also hasten to add:

    There are two exceptions to this, however:

    • Returning false or undefined (or omitting return altogether) will not dispatch the action
    • Returning a Promise will not dispatch the action

    So that bit provides a way to avoid triggering dispatch at all.