-2

I have an state that has an array of objects. I'm stuck trying to update a property of an object inside that array.

const [state, setState] = useState([obj = {key: "x"}, obj = {key: "y"}])

I'm trying to create a handleChange event to control an input element.

So far, I tried the code below where __index is a property that I use as an identifier.

  const handleChange = (event) => {
    setState((prevState) => [
      ...prevState.filter((otherObj) => otherObj.__index !== obj.__index),
      (obj = {
        ...prevState[obj.__index],
        description: event.target.value,
      }),
    ]);
  };
ghophri
  • 183
  • 1
  • 1
  • 12

1 Answers1

1

First, use the state correctly:

const [state, setState] = useState([
    {key: "x"}
    {key: "y"}
]);

Then copy the previous state and update the object you need, before returning it as the new state:

const handleChange = (e) => {
  setState((prevState) => {
    // Copy previous state into new state
    const state = [
      ...prevState,
    ];

    // Get the current object by using the id to match the key
    // Could be any other way to find the right object depending on the rest of your code
    const obj = state.find(obj => obj.key === e.currentTarget.id)
    obj.description = e.currentTarget.value;

    return state;
  });
}
Emre Koc
  • 1,481
  • 10
  • 18