0

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

2 Answers 2

1

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)
    }
  }
})
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.