I am new to React Hooks and I was creating an example with an object as Hook. I read that while changing the Hook its good practice to use the previous hook to change the same as we do with states using prevState. I created two input fields which will take my input and show the input in headings.
import React, {useState} from 'react'
function NameHook() {
const [name, setName] = useState({firstName: '', lastName: ''})
const changeName = e => {
setName( prevName => (
{
...prevName,
[e.target.name]: e.target.value
})
)
}
return (
<div>
<input
type="text"
value={name.firstName}
onChange={changeName}
name="firstName"
/>
<input
type="text"
value={name.lastName}
onChange={changeName}
name="lastName"
/>
<h1>{name.firstName}</h1>
<h1>{name.lastName}</h1>
</div>
)
}
export default NameHook
Now whenever I type the second character in the field I get the error
Cannot read property 'name' of null
I read in this answer that this is because REACT is recycling the event and changing the changeName function as below solves the error
const changeName = e => {
e.persist()
setName( prevName => (
{
...prevName,
[e.target.name]: e.target.value
})
)
}
But the code also works the same if I don't use the prevName and directly use setName with the current name value as below
const changeName = e => {
setName(
{
...name,
[e.target.name]: e.target.value
}
)
}
If the event is getting recycled is creating the problem then it should also create the problem when I am not using prevName because we are only changing the setName method in that. I am not getting why it is working now and why I am getting the error when I am using prevName.