Convert object to use spread operator?

Viewed 140

I have a case in redux reducers and I used an object.assign to take a copy of my state, and I want to transform it to new syntax spread operator"...state", how can I make it,

Without making a mutation!

case INCREASE_QUANTITY: {
      return Object.assign({}, state, {
        cart: state.cart.map(item => {
          if (item.product.id === action.productInfo.product.id) {
            return Object.assign({}, item, {
              quantity: action.quantity + 1,
            });
          }
          return item;
        }),
      });
    }
2 Answers

You open an object literal, start with ...state to spread that out into the new object, and follow it with the cart property (and the same concept for the inner one):

case INCREASE_QUANTITY: {
  return {
    ...state,
    cart: state.cart.map(item => {
      if (item.product.id === action.productInfo.product.id) {
        return {
          ...item,
          quantity: action.quantity + 1,
        };
      }
      return item;
    }),
  };
}

By doing it in that order, you ensure that cart (or quantity for the inner one) overrides the property from the spread. Later properties in in object literals "win" over earlier ones.

Object.assign({}, item, { quantity: action.quantity + 1 });
becomes
{ ...item, quantity: action.quantity + 1 }

case INCREASE_QUANTITY : {
    return {
        ...state,
        cart : state.cart.map(item => {
            if (item.product.id === action.productInfo.product.id) {
                return {
                    ...item,
                    quantity: action.quantity + 1
                }
            }
            return item;
        })
    };
}
Related