Search code examples
javascriptreactjstypescriptreduxredux-toolkit

How can I get the state value in the reducer of createSlice?


I'm using redux-toolkit in my react project. In a reducer of createSlice, I want to use the existing array of entities from the state and append the new array,before reducing the final state. But I'm unable to get the state value.

Here is the reducer code

export const usersSlice = createSlice({
  name: "users",
  initialState: initialUsersState,
  reducers: {
    usersCreated: (state: UsersState, action) => {
      // in real, return count from the server and append the entities on front-end only?
      const { count, entities } = action.payload;
      const existingEntities = state.entities;
      const newEntities = [...existingEntities, ...entities];
      const totalCount = state.totalCount+count;
      return {
        ...state,
        entities: newEntities,
        totalCount: totalCount,
        listLoading: false,
        error: null,
      };
    },
}});

When I debug the state.entites variable, it looks like this

enter image description here

Is there a way to access the current state value in reducer/extraReducer to recreate the state as per desire?

Because I assume directly working with state value outside the reducer would be a bad practice. Please guide me, if I'm wrong.

Edit

The code sandbox created by @Linda Paiste is working fine, that means we can access the state variable in reducer but we can't debug the state variable to dig deeper what is that state variable is holding at the moment, as Redux-toolkit is dealing the state in it's own way... As obvious from the debugging screenshot

enter image description here


Solution

  • You can only reference the current slice state.

    Therefore your only options are passing the desired entities as action's payload or implementing this action as a thunk createAsyncThunk and use getState() from its API.