0
  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],
                }));
1
  • 1
    Replace ...arr with ...prevState and you're golden. Commented Feb 6, 2023 at 7:15

1 Answer 1

3

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],
}));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.