Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Redux Toolkit determine property names on the state object?

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.

like image 385
ontley Avatar asked Sep 16 '25 02:09

ontley


1 Answers

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]
like image 74
Linda Paiste Avatar answered Sep 18 '25 16:09

Linda Paiste