'React hooks with multiple state values not working but separate state value works

I am changing my code with hooks with only basic knowledge. The example format below which is a separate state value with a conditional statement works with my input form but:

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [userName, setUserName] = useState("");
const [error, setError] = useState(null);


const onChangeHandler = event => {
   const { name, value } = event.currentTarget;

   if (name === "userEmail") {setEmail(value)}
   else if (name === "userPassword") {setPassword(value)}
   else if (name === "userName") {setUserName(value)}
};

when I try to put it inside a single state like the example below it does not work and goes directly to the error message:

const [newUser, setNewUser] = useState({
  userName: "",
  email: "",
  password: "",
  error: null,
});


const { userName, email, password, error } = newUser

const onChangeHandler = event => {
  const { name, value } = event.currentTarget;

  setNewUser({...newUser, [name]: value})
};

with the input field, that works on the separate state value, but doesn't work with the multiple state value and field is not clickable:

    <Form.Group>
      <Form.Control
        size="lg"
        type="text"
        placeholder="Username"
        name="userName"
        value={userName}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>
    
    <Form.Group> 
      <Form.Control
        size="lg"
        type="email"
        name="userEmail"
        placeholder="E-mail"
        value={email}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>

    <Form.Group>
      <Form.Control
        type={"password"}
        placeholder="Password"
        name="userPassword"
        value={password}
        onChange={event => onChangeHandler(event)}
        required
      />
    </Form.Group>


Solution 1:[1]

You are mixing up names. In the initial state you have following:

const [newUser, setNewUser] = useState({
  userName: "",
  email: "",
  password: "",
  error: null,
});

But while changing the values, you set the values to be userName , userEmail, userPassword. As mentioned in the JSX below, you added the name prop of each field.

Get the names synchronized and you are good to go!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Haider Ali Anjum