This error occurs because the setState
function is not being handled properly here.
Unlike the setState
method found in class components, useState
does not automatically merge update objects.
So we can say that the real question is:
How to change a single property of a state object using useState hook?
Solution 1: You can return a new object by spreading over previous state.
const handleChange = (e) => {
setObject((prevObject) => ({ ...prevObject, value: e.target.value }));
console.log(object);
};
Solution 2: You can create a new state object and completely replace the old one.
In this solution, you cannot guarantee that object has been refreshed to the latest version.
Also, even if it were, you're setting object to be the same object reference it currently holds, therefore it will not be recognised as a change and the value will not be set.
const handleChange = (e) => {
const temp = object;
temp["value"] = e.target.value;
setObject(temp);
console.log(object);
};
See these questions:
- Updating and merging state object using React useState() hook
- Cannot create property on string