How to setState a specific value of a particular parameter in reactjs

Viewed 92
this.state = {
  array: [1, 2, 3],
  objects: [{ id: 1 }, { id: 2 }, { id: 3 }]
}

How can I change the specific value of an object or array in the state without setStating the whole array/object?

something like

this.setState({ array[2]: 5 })
this.setState({ object[0].id: 0 })
2 Answers

You could use a helper function to set an element at an index and return that newly updated array

const array = [1, 2, 3]
const object = [{id: 1}, {id: 2}, {id: 3}]

const setElementAtIndex = (index, value, array) => [
  ...array.slice(0, index),
  value,
  ...array.slice(index + 1)
]

console.log(setElementAtIndex(0, 99, array))
console.log(setElementAtIndex(1, 99, array))
console.log(setElementAtIndex(2, 99, array))
console.log(setElementAtIndex(0, { ...object[0], id: 0 }, object))

this.setState({ array: setElementAtIndex(2, 5, array) })
this.setState({ object: setElementAtIndex(0, { ...object[0], id: 0 }, object) })

I would use map.

const state = {
     array: [1,2,3],
     objects: [{id: 1}, {id: 2}, {id: 3}]
}

const newArray = state.array.map((v, i) => i === 2 ? 5 : v);
const newObjects = state.objects.map((v, i) => i === 0 ? {...v, id: 0} : v);

console.log(newArray);
console.log(newObjects);

// this.setState({ ...this.state, array: newArray });
// this.setState({ ...this.state, objects: newObjects });

Related