Oliver D
Oliver D

Reputation: 2889

Convert object to use spread operator?

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;
        }),
      });
    }

Upvotes: 2

Views: 322

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

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.

Upvotes: 3

giuseppedeponte
giuseppedeponte

Reputation: 2391

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;
        })
    };
}

Upvotes: 1

Related Questions