Let's say we want to keep the filters of a list in a state.
const [filters, setFilters] = useState([])
And one sample of filters array could be:
[
{
"property": "Name",
"value": "John",
"operator": "eq"
},
{
"property": "Age",
"value": "18",
"operator": "gt"
},
{
"property": "IsMarried",
"value": true,
"operator": "eq"
}
]
Now let's say I want to change 18 to 24. This is my code. But it does not work:
const setFilter = (property, value, operator) => {
var isAdded = false;
for (var i = 0; i < filters.length; i++) {
if (filters[i].property === property) {
if (filters[i].operator && operator && filters[i].operator === operator) {
const otherFilters = filters.filter(i => i.property !== property && i.operator !== operator)
setFilters([...otherFilters, {
property,
operator,
value
}])
isAdded = true
break;
}
}
}
if (!isAdded) {
setFilters(previousFilters => [...previousFilters, {
property,
operator,
value
}])
}
}