0

The first state variable is newUser and it's initialized to an empty string. There is a form with an input field to change newUser to whatever the input is. There are also two more state variables: users, which is initialized to {currentUser: false}, and userInfo, initialized to {id: "example", amount: "x", users} where users is that same state variable. I'm building a button to add users to the users state variable. onCLick the button calls the following function:

const handleAdd = e => {
       
        e.preventDefault();
        setUsers({...users, newUser: false})
        setUserInfo({
            id: "example",
            amount: "x",
            users
        })
        setNewUser("")
    } 

The problem I'm running into is that instead of adding the value of the variable newUser as a key to the object, the key that is added to the object is newUser. Ex: if I type "john" into the input field and click the button, users should look like this:

{
  currentUser: false,
  "john": false
}

and instead it looks like this:

{
  currentUser: false,
  newUser: false
}

How can I add the actual value of the variable newUser as the key instead of the variable itself?

Leo Troper
  • 17
  • 2
  • FYI you should use `setUsers((prev) => ({...prev, [newUser]: false}))`. See https://reactjs.org/docs/hooks-reference.html#functional-updates – Phil Oct 05 '22 at 03:45

1 Answers1

1

You can try this instead

setUsers(user => {...user, [newUser]: false})
otejiri
  • 1,017
  • 6
  • 20