Default reducer for slice
See original GitHub issueCurrently it seems there’s no way to add a default reducer to a slice. This is useful when using libraries like normalizr
with an entities
slice. The entities
slice listens for all actions and then checks for the presence of entities
in the payload.
Currently I had to create an old fashioned reducer for using normalizr
. It would be useful if createSlice
offers a defaultReducer
or something like that that runs for all actions.
This is what I’m currently using
import merge from 'lodash/merge'
import produce from 'immer'
const entitiesSliceName = 'entities'
function entitiesReducer(baseState = {}, { payload }) {
if (!payload || !payload.entities) return baseState
return produce(baseState, draftState => {
merge(draftState, payload.entities)
})
}
export default {
reducer: entitiesReducer,
name: entitiesSliceName,
}
This is what I think could be usefull
import { createSlice } from '@reduxjs/toolkit'
import merge from 'lodash/merge'
const entitiesSlice = createSlice({
name: 'entities',
initialState: 0,
defaultReducer: (state, { payload = {} }) => merge(state, payload.entities),
})
export default entitiesSlice
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:13 (6 by maintainers)
Top Results From Across the Web
createSlice - Redux Toolkit
A function that accepts an initial state, an object of reducer functions, and a "slice name", and automatically generates action creators and ...
Read more >How To Setup Redux Slices with Redux Toolkit - SoftKraft
`createSlice` takes an object of reducer functions, a slice name, and an initial state value and lets us auto-generate action types and action...
Read more >Understanding createSlice in Redux Toolkit — ReactJS.
createSlice is a higher order function that accepts an initial state, an object full of reducer functions and a slice name. It automatically...
Read more >slice, action and reducers, what are they? - Stack Overflow
Reducers are just responses to our corresponding called action to perform on our immutable state and thus returning a new state. optionally you ......
Read more >A powerful React + Redux Toolkit pattern (reuseable state ...
Summation · It utilises all features of Redux Toolkit to provide reusable slices, actions, and reducers. · Each slice is completely independent, ...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
ok my apologies. I just mean it would be nice to have an internal utility similar to this
and use it like this
Okay, misunderstood you then 😃