/ javascript

Redux with example: Share state between two reducers

There are several approaches that can be used. One of them is using "async action creators" using redux-thunk.

What is thunk?

From redux-thunk docs

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

Basically it's an action creator that returns a function to perform asynchronous dispatch & receives the getState and dispatch functions as parameters.

The situation

Let's assume that we have two different reducers for friends and chatBoxes store and we want share our friends data from friendsReducer to chatBoxReducer.

Async thunk action

Now we are sharing data between two reducers!

ChatBoxReducer

Basically you have the full store in your disposal with getState() in your action creators. That's it!

Edit: Redux FAQ covers this topic and more.