Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux Toolkit - How to share an action between slices

I am using Redux Toolkit and have three components with a slice for each component: A, B, C.

I need component A to dispatch an action and components B and C to react to it. How can I achieve that having all components not being dependant on each other, similar to a pub/sub pattern?

like image 660
elm Avatar asked Dec 01 '25 23:12

elm


1 Answers

Firstly, add extraReducers in components B and C reacting to the action.

However, you risk ending up in the circular reference problem. where one component references the other and vice versa.

The authors mentions a solution on github which i had use of. Namely, separating the shared reducers into a separate file. My implementation of this is the following:

  • featureA/byId/actions.js contains actions defined with createAction.
  • featureB/byId/actions.js contains actions defined with createAction.

Each createAction is an action similar to the following:

const createTodo = createAction("todos/createTodo");
  • featureA/byId/reducer.js imports its extraReducer-actions from both action.js-files above.
  • featureB/byId/reducer.js imports its extraReducer-actions from both action.js-files above.

Result: actions used in multiple reducers without circular reference problems.

like image 61
Simon Avatar answered Dec 06 '25 04:12

Simon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!