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

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.

don't use combineReducers.

Example

replace this code

export const a = combineReducers({
  app,
  posts,
  intl,
  products,
  pos,
  cats,
});

with

export default (state = {}, action) => {
  return {
    app: app(state.app, action, state),
    posts: posts(state.posts, action, state),
    intl: intl(state.intl, action, state),
    products: products(state.products, action, state),
    pos: pos(state.pos, action, state),
    cats: cats(state.cats, action, state),
  };
};

reducer would be like

const reducer = (state = initialState, action, root) => {....}

Ask yourself whether you've structured your reducers correctly. If a and b are not independent of one another, why are they separate reducers? I would try to merge them into a single reducer.


As David L. Walsh said, probably you should structure your reducers in a more logical way.

BUT If you still think you need it, you can use a thunk Middleware. (https://github.com/gaearon/redux-thunk) Redux Thunk middleware allows you to write action creators that return a function instead of an action.

Redux Thunk offers you a way to read the current state of the Redux store. In addition to dispatch, it also passes getState as the second argument to the function you return from your thunk action creator.

export function action() {
    return function(dispatch, getState){
        const state = getState()
        dispatch({
            type: "ACTION_WITH_SOME_PART_OF_STATE,
            some_part_of_state: state.some_part
        })   
    }
}

Tags:

Redux