Search code examples
javascriptreactjsstatedestructuring

How to update a single property in a React state (function component)


I want to update a state with a couple of values from a form with a single change handler in a function component. I cannot figure out how to set a single property in the state in a proper way. I have seen this works in a class component.

import React, {useState} from 'react'
import ReactDOM from 'react-dom'

export function Example(){
  const [user, setUser] = useState({nickname: '', age: 0})

  const handleChange = event => {
    const { name, value } = event.target
    setUser({ [name]: value })
  }

  return(
     <form>
       <input name="nickname" onChange={handleChange} />
       <input name="age" onChange={handleChange} />
       <button onClick={(e) => {
         e.preventDefault()
         console.log(user)
        }}>Show User</button>
     </form>
  )
}

ReactDOM.render(
    <Example />,
    document.getElementById('app')
);

The code above does not work the way I want to since it always overrides the whole state and not only the corresponding property.

I receive:

Object {age: "24"}
Object {nickname: "Lala"}

I want:

Object {age: "24", nickname: "Lala"}

What is the best practice to achieve this?


Solution

  • Try to do it this way:

    const handleChange = event => {
        const { name, value } = event.target
        setUser({ ...user, [name]: value })
    }