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
}
})
[state.cart[itemIndex]]: {