Search code examples
reactjsflux

flux: how to update a store from within a store


My use case is straightforward. I want to add a notification message to my NotificationStore to display an informational banner to the user in the event that my primary store has been successfully updated.

The simplest way to achieve this appears to be raising an action from within my primary store:

   onSaveRule: function() {
        localStorage.setItem("rule", JSON.stringify(_state));
        action.fire("rule successfully saved!"); //mutates NotificationStore
    },

However, the action.fire line throws the following run-time exception:

Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch.

Clearly, calling an action from within a store is an anti-pattern. So what is the correct way to achieve the desired effect?


Solution

  • Using storeA and storeB as an example, where your original idea is to have storeA firing an action and have storeB listening to the same action.

    Instead of directly firing an action within storeA, you should have storeB directly listening to storeA state change triggers. Meaning upon storeA state changes and calls trigger to notify your components, storeB will also be notified by the same trigger. storeB can then call getters to retrieve new states from storeA.

    In this pattern, storeB is a derived store of storeA. This preserves the unidirectional data flow philosophy of the flux pattern.