useState with Object


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 (
 //can overwrite previously entered input
      <input type="text" value={name.firstName} onChange={e =>setName({})/>
      <input type="text"value={name.lastName} onChange={e =>setName({})/>
//fixed using the spread operator
         <input type="text" value={} onChange={e =>setName({})/>
      <input type="text"value={} onChange={e =>setName({})/>
      <h2> Your first name is {name.firstName}</h2>
      <h2> Your last name is {name.lastName}</h2>
export default HookCounterThree

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