Friday 2 October 2020

How to get a state value in the reducer of createSlice in Redux-Toolkit

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.



from How to get a state value in the reducer of createSlice in Redux-Toolkit

No comments:

Post a Comment