Taylor Austin
Taylor Austin

Reputation: 6007

Is this the correct way to copy state in a Redux Reducer?

In the past I have used Object.assign() and done it that way, but recently I was told to use the spread operator. I was wondering if this was the correct way of doing it or if this is mutating the state?

import constants from '../constants';

const initialState = {
  all: null
};

export default (state = initialState, action) => {
  switch (action.type) {
    case 'ITEM_ADDED':
      return { ...state, all: state.all.push(action.data) };
    default:
      return { ...state };
  }
};

Upvotes: 0

Views: 4356

Answers (1)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93323

You did a mutation when you used Array::push method :

  return { ...state, all: state.all.push(action.data) };

And the right way is to use the spread operator also to append object to array instead of push :

  return { ...state, all: [...state.all, action.data] };

Upvotes: 5

Related Questions