0

I need to change the value of a specific key when returning an object. I don't know if there is a way to do this.

Is hard to tell exacty what I need, but in the code below is easy to get:

return {
  ...state,
  cart: [
     ...state.cart,
     state.cart[itemIndex]: {  // <- This is what I want, but this way doesn't work
       {
         productId: action.product.productId,
         quantity: action.quantity
       },
     }
  ]
}
2
  • 2
    Show the action payload that you're passing to your reducer and the sample of your state that you attempt to modify. Commented Sep 8, 2020 at 19:59
  • [state.cart[itemIndex]]: { Commented Sep 8, 2020 at 20:12

1 Answer 1

1

If you are trying to replace an item in an array, you'll need to use array methods to get to the right index.

You can use Array.map() to set the item at the requested index:

return {
  ...state,
  cart: state.cart.map((item, index) => 
    index !== itemIndex ? item : {
      productId: action.product.productId,
      quantity: action.quantity
    }
  )
}

Or use Array.slice() with array spread:

return {
  ...state,
  cart: [
    state.cart.slice(0, itemIndex),
    {
      productId: action.product.productId,
      quantity: action.quantity
    }
    state.cart.slice(itemIndex + 1),
  ]
}

A shorter option would be to clone the array, and just replace the item in the requested index:

const updatedCart = [...state.cart]
updatedCart[itemIndex] = {
  productId: action.product.productId,
  quantity: action.quantity
}

return {
  ...state,
  cart: updatedCart
}

Using immer:

import produce from 'immer'

return produce(state, draftState => {
  draftState.cart[itemIndex] = {
    productId: action.product.productId,
    quantity: action.quantity
  }
})
Sign up to request clarification or add additional context in comments.

4 Comments

Just to be clear, the way that I want doesn't exists?
The shorter option is great, thanks! I don't know why the heck I didn't think this way xD
Nope. Array spread just shallow clones the entire array to a new one. Everything you add after the spread would be last. In addition, the syntax [key]: value doesn't work with arrays.
You should also checkout immer - it does the immutable heavy lifting for you.

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.