BartolV9
BartolV9

Reputation: 13

How to modify state in reduxjs/toolkit with React and TypeScript

When i worked with react-redux i updated the state like this:

case CartActionTypes.ADD_ITEM:
  return {
    ...state,
   cartItems: [...cartItems, { action.payload }];
  };

Now i'm using reduxjs/toolkit with slices, etc.

Should i update the state in the same way or maybe using .push method like this:

export const cartSlice = createSlice({
  name: 'cart',
  initialState: initialState,
  reducers: {
    addItemToCart(state, action) {
      state.cartItems.push(action.payload);
    },
}

Should i always return the state like i did usin

Upvotes: 0

Views: 1305

Answers (2)

Lin Du
Lin Du

Reputation: 102207

See Mutating and Returning State doc

Immer expects that you will either mutate the existing state, or construct a new state value yourself and return it, but not both in the same function! For example, both of these are valid reducers with Immer:

const todosSlice = createSlice({
  name: 'todos',
  initialState: [],
  reducers: {
    todoAdded(state, action) {
      // "Mutate" the existing state, no return value needed
      state.push(action.payload)
    },
    todoDeleted(state, action.payload) {
      // Construct a new result array immutably and return it
      return state.filter(todo => todo.id !== action.payload)
    }
  }
})

Upvotes: 1

Pierre Glandon
Pierre Glandon

Reputation: 23

State becomes "mutable" when you are defining reducers inside RTK createSlice. You can therefore use push to update your state without returning it.

Upvotes: 0

Related Questions