from some input fields I get each id and value when they click, now I want to Destructur the id from the user and update the only field.
this my user
const [user, setUser] = useState({
name: 'user name',
email: 'user email',
address: 'user address',
phone: 'user phone',
})
my html elements
<input className='w-100 mb-2' type="text" name="phone"
onBlur={handleUserUpdate}
required id="phone" placeholder='Phone'/>
<input className='w-100 mb-2' type="text" name="address"
onBlur={handleUserUpdate}
placeholder="Address" required id="address"/>
my function
const handleUserUpdate = event => {
const {id, value} = event.target
console.log(id, value)
// here id should address or phone but error
const { id,...rest} = user
const newUser = {value, ...rest}
console.log(newUser)
}
CodePudding user response:
// Destructure the value from the event
const { name, value } = event.target
// Set the new state
setUser({
...user
[name]: value
})
CodePudding user response:
i assume the variable id
value have same name as the key of object user
const handleUserUpdate = event => {
const {id, value} = event.target
setUser(prev => {...prev, [id] : value })
}