I am trying to learn hooks but have a problem with an object. Looks like useState doesn’t treat my object as an object and I can’t get hold of the second value.
function App() { const [fullName, setFullName] = useState({ fName: "", lName: "" }); function handleChange(event) { const { value, name } = event.target; setFullName((prevValue) => { if (name === "fName") { return { fName: value, lName: prevValue.lName }; } else if (name === "lName") { return { fName: prevValue.fName, lname: value }; } }); } console.log(fullName.fName); console.log(fullName.lName); return ( <div className="container"> <h1>Hello {fullName.lName}</h1> <form> <input name="fName" onChange={handleChange} placeholder="First Name" value={fullName.fName} /> <input name="lName" onChange={handleChange} placeholder="Last Name" value={fullName.lName} /> <button>Submit</button> </form> </div> ); }
When I console.log the lName, “undefined” pops up, while fName works perfect.
Advertisement
Answer
In the else if (name === "lName")
return statement you’re returning a key named lname
instead of lName
.