When a list of categories becomes available in store A, select one category and set its ID in store B

36 Views Asked by At

I have two stores - GroupsStore and ItemsFilterStore. The ItemsFilterStore's state should contain a choice of a single Group from the groups available in the GroupsStore, but:

  • the groups are not initially available in the GroupsStore, so the choice in the ItemsFilterStore cannot initially be made (the constructor initializes it to null).

  • once the groups become available in the GroupStore, I need to perform an action that will select one group (according to some logic) and set its ID in the ItemsFilterStore.

THE PROBLEM:

I read EVERYWHERE that triggering actions from action handlers in a store is an antipattern.

So how do I engineer this correctly?

1

There are 1 best solutions below

2
Gleb Kostyunin On

Well, I came up with 2 possible ways of handling this case. Just for the clarity, let's say you have an action getGroups that fires the request to the source. When the request is successful it fires the action resultsRecieved, which GroupsStore handles.

1) You can listen to the resultsRecieved action in both stores and handle the results to update the ItemsFilterStore. But in that case you might need to pull out the group selection logic from GroupsStore into some utility file, that can be imported and used in both stores, if this is possible.

2) You can listen to the getGroups action in both stores. In the ItemsFilterStore handler for that action you can utilise Alt's wait-for method which signals that this store depends on another store for its data and should wait for it to be updated. So the getGroups handler in ItemsFilterStore might look something like this in the end:

getGroups() {
    this.waitFor(GroupsStore);
    var groups = GroupsStore.getState().groups;
}

I am not fully sure how good wait for will work with the async source requests, since I only used it to wait for synchronous operations.