skip to Main Content

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


  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..

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search