import { createSlice } from '@reduxjs/toolkit'
export const countersSlice = createSlice({
name: 'based? based on what',
initialState: [0, 0, 0, 0],
reducers: {
updateCounter: (state, action) => {
var id = action.payload.id
var value = action.payload.value
state[id] += value
}
}
})
export const { updateCounter } = countersSlice.actions
export const selectCount = id => state => state.counter[id]
export default countersSlice.reducer
Why is it that, in the selectCount
line, I have to use state.counter
when .counter
isn't referenced anywhere else in the slice? I do like that it's .counter
but I just want to understand how it's coming up with that property.
The name
property in createSlice
is used internally by redux-toolkit to create the names for your actions. If the name is 'counter'
then the updateCounter
action will have { type: 'counter/updateCounter' }
. If it's 'abc'
then your action will have { type: 'abc/updateCounter' }
. This name doesn't matter. As long as it's different from any other reducers in your app then you're fine.
If I change .counter to something else, it breaks the entire project
Now you are talking about something else, which is how you select your data from the root state of your app.
export const selectCount = id => state => state.counter[id]
This selector function assumes that the reducer from this slice will be on the counter
property of your root reducer. The location of this reducer relative to the root state is determined by the property key when you combine your reducers with configureStore
or combineReducers
.
Your current selector assumes that your store looks like this:
import {configureStore} from '@reduxjs/toolkit';
import counterReducer from './yourReducerFile.js'
export default configureStore({
reducer: {
counter: counterReducer
}
});
This property key often matches the name
of your slice, but it doesn't have to match.
You can use any property key as long as the selector function uses the same one. For example:
export default configureStore({
reducer: {
someOtherProperty: counterReducer
}
});
export const selectCount = id => state => state.someOtherProperty[id]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With