0

I'm looking for a way to update a single index of an object's values that are an array while saving the state of the other values. I tried using a spread operator, but I'm getting an error.

const [points, setPoints] = useState({"x": [46, 168, 292, 415, 537, 660] , "y":[60, 192, 324, 454]});

const update = (e) => {
    setPoints(points => ({
      ...points,
      x[0]: e
    }));
  };

I am unsure how to update the specific index.

Thanks!

2

1 Answer 1

1

Be more focussed in your update

Build up the new value of the object from the parts of the old object. Remember that x and y are independent properties of that object. So you can simply let y flow through unchanged, but need to build a new x.

A simple way of building the new x is creating a new array, starting with e, and then taking all remaining items of the old x, starting from item #1 (i.e. omitting #0).

I've made the function name more clearly indicate you are only updating x[0].

const [points, setPoints] = useState({"x": [46, 168, 292, 415, 537, 660] , "y":[60, 192, 324, 454]});

const updateX0 = (e) => {
    setPoints(points => ({
      x:[e, points.x.slice(1)],
      y: points.y
    }));
  };

Not the answer you're looking for? Browse other questions tagged or ask your own question.