How can I append a state object in react

  const [arr, setArr] = useState({
      value: [],
        });

//I want to append the value on the state object but its overwriting it.

  setArr((prevState) => ({
                    ...arr,
                    value: [...prevState.value, res.data],
                }));

>Solution :

You can set new state by comparing old state data and push new data inside setArr function.

So your new code will be:

setArr((prevState) => ({
  ...prevState,
  value: [...prevState.value, res.data],
}));

Leave a Reply