0

I am fundamentally misunderstanding React hooks, especially the useState function. Why doesn't the code below update the index of the old array, and instead set the value of trick to 1? I understand how to push a new item onto an array with React hooks, but how do you update existing values?

const [trick, modifyTrick] = useState([null, null, null, null]);

const identityTrick = () => {
    modifyTrick(oldTrick => oldTrick) //works
}

const updatedTrick = () => {
    modifyTrick(oldTrick => oldTrick[0] = 1) //sets the entire value of trick to 1
}
Perplexityy
  • 561
  • 1
  • 9
  • 26
  • Possible duplicate of [How do I update states onchange in an array of object in React Hooks](https://stackoverflow.com/questions/55987953/how-do-i-update-states-onchange-in-an-array-of-object-in-react-hooks)? – crashmstr Feb 17 '20 at 12:48

3 Answers3

1

Try this one

  const updatedTrick = () => {
    modifyTrick(oldTrick => {
      let newTrick = [...oldTrick];
      newTrick[0] = 1;
      return newTrick;
    })
  }
Max
  • 582
  • 1
  • 4
  • 13
1

You can also do it like this:

const updateTrick = () => {
    modifyTrick(oldTrick => {
      oldTrick[0] = 1;
      return oldTrick;
    });
};
Eliecer Chicott
  • 541
  • 4
  • 7
1

If you provide modifyTrick a function, the return value will be the new value of trick.
The return value of your function is 1, so that's why trick is set to 1.

oldTrick[0] = 1 //this expression returns 1.

Modify oldTrick array in your modifyTrick function, and than return it:

const updatedTrick = () => {
    modifyTrick(oldTrick => {
       oldTrick[0] = 1

       return oldTrick;
    });
};
Ido
  • 5,363
  • 2
  • 21
  • 30