How would I go about updating an array inside of an object using useState. My hook looks something like this:
const [currentUser, setcurrentUser] = useState({firstname:"adam" , classes:["discrete", "calc 2", "physics"]});
I’ve been trying to set currentUser.classes equal to a new array of classes but been running into errors.
2
Answers
You can try this method.. If you are still facing issues just let me know..
in the above method… I use react hook useEffect to change the value of current User classes..
Couple things to remember when dealing with objects in JavaScript. If you try changing the value of
currentUser
directly, likecurrentUser.firstname = "joe"
the React state won’t update.Here is a CodeSandbox to give you an example of what you are trying to do
https://codesandbox.io/s/suspicious-browser-gdkvkm?file=/src/App.tsx:235-303
This is the key part
setcurrentUser((oldVal) => ({ ...oldVal, classes: ["new class"] }));
What is happening here is that you can use
setcurrentUser
to get the old value, then create a new object with the old values and whatever changes you want to make.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
The spread operator makes this pretty easy,
...oldVal
basically copies the values of the current object, and then we overwriteclasses