Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actions in multiple slices in Redux toolkit

Tags:

The Redux toolkit docs mention using actions (or rather action types) in multiple reducers

First, Redux action types are not meant to be exclusive to a single slice. Conceptually, each slice reducer "owns" its own piece of the Redux state, but it should be able to listen to any action type and update its state appropriately. For example, many different slices might want to respond to a "user logged out" action by clearing data or resetting back to initial state values. Keep that in mind as you design your state shape and create your slices.

But, “keeping that in mind”, what is the best way to achieve this, given that the toolkit puts the slice name at the start of each action type? And that you export a function from that slice and you call that single function to dispatch the action? What am I missing? Does this have to be done in some way that doesn’t use createSlice?

like image 649
Jonathan Tuzman Avatar asked Apr 17 '20 03:04

Jonathan Tuzman


People also ask

Does Redux support multiple actions?

Well, no matter what you pass to dispatch , it is still a single action. Even if your action is an array of objects, or a function which can then create more action objects!

What is a slice in Redux toolkit?

What is createSlice in Redux Toolkit? createSlice is a higher order function that accepts an initial state, an object full of reducer functions and a slice name. It automatically generates action creators and action types that correspond to the reducers and state.

What is extra reducers in Redux toolkit?

extraReducers ​ One of the key concepts of Redux is that each slice reducer "owns" its slice of state, and that many slice reducers can independently respond to the same action type. extraReducers allows createSlice to respond to other action types besides the types it has generated.


1 Answers

It looks like this is what extraReducers is for:

One of the key concepts of Redux is that each slice reducer "owns" its slice of state, and that many slice reducers can independently respond to the same action type. extraReducers allows createSlice to respond to other action types besides the types it has generated.

It is a little strange that the action dispatcher should know which reducer the action belongs. I'm not sure the motivation of having reducers and extraReducers, but you can use extraReducers to allow several slices to respond to the same action.

like image 193
jmellman Avatar answered Sep 17 '22 15:09

jmellman