0

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
        }])
    }
}

1 Answer 1

1

You can just map over filters state and change value or operator if the property matches as:

CODESANDBOX LINK

  function setFilterValue(property, value, operator) {
    return filters.map((filter) => {
      return filter.property === property
        ? { property, value, operator }
        : filter;
    });
  }

  function changeFilterValue() {
    const value = setFilterValue("Age", "24", "gt");
    setFilters(value);
  }
Sign up to request clarification or add additional context in comments.

2 Comments

But it only changes the state directly inside the state variable. It does not call React's setFilters set state function.
It is not changing state directly we are returning new state (i.e array) and which is argument of setFilters . Answers updated

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.