Reputation: 25
I'm trying to make an update on an Object that is in the state using React Hooks, but when I try to update the Objet the function .map
stop working.
First I have this handleCheckedFilterChange
function and it change the state Object but the component was not re-render:
const handleCheckedFilterChange = (name) => {
let prevFilters = filters;
for (let filter in prevFilters) {
if (prevFilters[filter].name === name) {
prevFilters[filter].checked = !prevFilters[filter].checked;
prevFilters[filter].filters.map((value) => {
value.disabled = !value.disabled;
});
setFilters(prevFilters);
break;
}
}
};
So then I change it to this one to make the component render again:
const handleCheckedFilterChange = (name) => {
let prevFilters = { ...filters };
for (let filter in prevFilters) {
if (prevFilters[filter].name === name) {
prevFilters[filter].checked = !prevFilters[filter].checked;
prevFilters[filter].filters.map((value) => {
value.disabled = !value.disabled;
});
setFilters(prevFilters);
break;
}
}
};
But this second one generates me an error:
TypeError: filters.map is not a function
The error is when I call the following:
const renderCards = filters.map((filter) => (
<div className="card text-center">
...
</div>
));
Upvotes: 0
Views: 255
Reputation: 15166
In the first option you are trying to modify the state directly which is not allowed in React's useState
and that's why it is not rendering your expected change.
The problem with the second option is your are trying to use {}
instead of []
. Try as:
let prevFilters = [ ...filters ];
The reason behind is .map()
is a function on arrays and not on objects.
Upvotes: 2