useState with Object

PHOTO EMBED

Tue Sep 06 2022 19:40:33 GMT+0000 (UTC)

Saved by @bfpulliam #react.js

import React, {useState} from 'react'

function HookCounterThree() {
  
  const[name, setName]= usestate({ firstName:'', lastName:'' })
  return (
    <form>
 //can overwrite previously entered input
      <input type="text" value={name.firstName} onChange={e =>setName({firstName:e.target.value})/>
      <input type="text"value={name.lastName} onChange={e =>setName({lastName:e.target.value})/>
//fixed using the spread operator
         <input type="text" value={...name.firstName} onChange={e =>setName({firstName:e.target.value})/>
      <input type="text"value={...name.lastName} onChange={e =>setName({lastName:e.target.value})/>
      <h2> Your first name is {name.firstName}</h2>
      <h2> Your last name is {name.lastName}</h2>
    </form>
  )
}
export default HookCounterThree
content_copyCOPY

You have to manually handle the manually merging of the new object after update. To do this you have to use the spread operator. ...name make a copy of the name object and then update with the onChange.