-2
case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const items = state.items
  items[index][name] = value
  return { ...state, items }

Is there a succinct way to use spread operators to implement the code above?

vedder
  • 1
  • 1
  • 2
    Not an answer, but just feedback. In `items[index][name] = value` you're mutating the redux state. That's not recommended. You would want to copy the array first, `const item = [...state.items]`; Then it would be ok to mutate with ``items[index][name] = value`; – jonahe Sep 12 '17 at 22:06
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator – Gopinath Kaliappan Sep 13 '17 at 04:19
  • Need more info on the structure of you state object – Shubham Khatri Sep 13 '17 at 09:55

1 Answers1

0

Thank you for your comments. The structure of my array of objects is below, where there can be many objects in the items array.

items: [{
  name: '',
  code: '',
  quantity: '',
  netBottlePrice: '',
  netCasePrice: '',
  caseSize: '',
  volume: '',
  volumeUnit: '',
  amount: ''
}]

I found a way to accomplish updating the redux state without mutating it using spread operators:

case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const item = { ...state.items[index], [name]: value }
  const items = [...state.items.slice(0, index), item, ...state.items.slice(index +1) ]
  return { ...state, items }
vedder
  • 1
  • 1