0

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.

  • What have you tried? What errors are you running into? – vighnesh153 May 01 '23 at 01:56
  • ive tried"currentUser.classes = someNewArray" which hasnt seemed to work for me. I have ran into a weird error saying "typeError: h is not a function" I believe its because i was trying "setCurrentUser(currentUser)". the reasons i tried that was because the page wasnt rerendering after editing the array – Adam Farrow May 01 '23 at 01:57
  • 3
    Can you paste the state trace in the question? On a side note, you should be updating a state using its setter. Example: `setCurrentUser(o => ({...o, classes: someNewArray}))` – vighnesh153 May 01 '23 at 02:00
  • Does this answer your question? [Updating an object with setState in React](https://stackoverflow.com/questions/43638938/updating-an-object-with-setstate-in-react) – programandoconro May 01 '23 at 02:28

2 Answers2

1

You can try this method.. If you are still facing issues just let me know..

const [currentUser, setcurrentUser] = useState({firstname:"adam" , classes:["discrete", "calc 2", "physics"]});

const newArray = ["Good", "Bad", "Neutral"]

useEffect(()=>{
setCurrentUser({...currentUser,classes:newArray})
},[currentUser])

in the above method... I use react hook useEffect to change the value of current User classes..

Varun Kaklia
  • 366
  • 4
  • 9
0

Couple things to remember when dealing with objects in JavaScript. If you try changing the value of currentUser directly, like currentUser.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 overwrite classes

AshotN
  • 395
  • 4
  • 15