I have a problem with React useState hook. I have a nested component that is inside of an array like this:
export default ParentComponent = () => {
return (
<>
{ someArray.map( (item, i) => {
<ChildComponent key={i} someData={item} />
}) }
</>
)
}
Now, the ChildComponent receives an object (standard JSON) with some values, for instance {firstName:’John’, company:’The Office’}, so ChildComponent initializes like this:
export default ChildComponent = ({someData}) => {
const [ dataInChild, updateData ] = useState(someData);
return (
<div>
<input name="firstName" value={dataInChild.firstName} />
<input name="company" value={dataInChild.company} />
</div>
)
}
It works fine if I edit the values on the input fields, I have no problem at all. I also have other methods to control the onChange and even onBlur, but that’s not the issue.
The problem is when the parent deletes one element of the array. For instance, let’s say the array has something like this:
[
{firstName: "Steve", company: "The Office"},
{firstName: "Gunther", company: "Central Perk"},
{firstName: "Clark", company: "The Daily Planet"}
]
If I delete, say, the second element, the array is updated as:
[
{firstName: "Steve", company: "The Office"},
{firstName: "Clark", company: "The Daily Planet"}
]
Deleting the element is with a simple .splice() in the array. I have tested and debugged a few days now and the array does update as expected. However, when the component re-renders, I debugged and the useState hook does receive the updated data, but when running this line of code
const [ dataInChild, updateData ] = useState(someData);
//Debugging here right after calling useState, dataInChild has previous value
the variable someData does contain the updated element of the array but the variable dataInChild still keeps the original value. By that I mean that the array does render 2 elements instead of 3, but the second item is still Gunther, when it should be Clark.
Any thoughts?
6