All Challengesintermediate

React useState with objects

A subtle bug AI commonly introduces when updating state that is an object.

reactuseStateobjectsspread operator
javascript
function ProfileForm() {
  const [form, setForm] = React.useState({
    name: '',
    email: '',
    bio: ''
  })

  function handleChange(field, value) {
    setForm({ [field]: value })
  }

  return (
    <div>
      <input onChange={e => handleChange('name', e.target.value)} />
      <input onChange={e => handleChange('email', e.target.value)} />
    </div>
  )
}

Question

What is the bug in handleChange, and what happens when you type in the name field then the email field?