Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 490
thiloilg Avatar asked Sep 08 '26 00:09

thiloilg


2 Answers

Try to do it this way:

const handleChange = event => {
    const { name, value } = event.target
    setUser({ ...user, [name]: value })
}
like image 114
nickelman Avatar answered Sep 10 '26 14:09

nickelman


Actually you are very close to the solution in the following line

  setUser({ [name]: value })

But you need to ensure the persistency of the legacy values that this input doesn't touch, therefore you need to change it to

  setUser({ ...user, [name]: value })
like image 30
windmaomao Avatar answered Sep 10 '26 12:09

windmaomao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!