Search code examples
redux

Redux - Is there any way to access store tree in reducer?


In my case, I have a store like:

{
  aa: {...},
  bb: cc  // the result of computing with aa
}

I need to update aa and bb at the same time, but bb need to get the latest computation of aa.

Here is some code(React.js):

onClick(e) {
  const { dispatch, aa, bb } = this.props;

  dispatch(updateAa());
  dispatch(updateBb(aa)); // can not get the latest computation of aa, it is the last computation..
}

So, is this mean that I need to get aa in bb's reducer?

And How can I do it?

Hope for helps!, Thanks!


Solution

  • There are several possibilities, but it's tough to say which is best, given the vagueness of the code.

    • Ideally, your store should be normalized, meaning that each piece of data is only available in one place. Then you would calculate derived data after reading the store, such as when you use the selector pattern described in the guide to map the state of the store to what you might consider a materialized view that will be sent to your components as props. In this workflow, aa and bb would each be produced by selector functions, rather than stored in that store itself.
    • You could leave the reducer that updates aa and bb outside of combineReducers, so that it sees the whole state, rather than the state scoped down to aa and bb.
    • You could factor out your calculation code into a helper that could be called by updateAa and updateBb, and pass enough info in each action to make the calculation.
    • You could calculate the update before dispatching, so that the action contains the right value.