Reputation: 693
I have an objects array like this below:
const [categories, setCategory] = useState([
{ text: "a", active: false },
{ text: "b", active: false },
{ text: "c", active: false },
{ text: "d", active: false }
]);
and I want to update the active fields to be true. I tried something like this but it doesn't work correctly at all:
const clearFilters = () => {
setCategory(categories.map((m) => (m.active = true)));
};
Upvotes: 1
Views: 38
Reputation: 318
const clearFilters = () => {
setCategory(categories.map((category) => ({...category, active: true})));
};
This must work. ".map" s callback function will be executed for every item of array, and every time will expect from you the new changed item. So you must return the new changed item. In my example above I used ES6 destructuring syntax, if you use ES5 it will be like this.
const clearFilters = () => {
setCategory(categories.map((category) => ({text: category.text, active: true})));
};
And yes, if you return the object in arrow function right away instead of executing function, you must put it into parentheses, otherwise it will understand it as function body, not object
Upvotes: 1
Reputation: 2635
Try something like below:-
const clearFilters = () => {
const clearedCategories = categories.map(m => {
m.active = true;
return m;
});
setCategory([...clearedCategories]);
};
Upvotes: 1