DEV Community

Maria del Carmen Santiago
Maria del Carmen Santiago

Posted on

How to avoid infinite loops onIonChange.

Backstory

I encountered a problem at work while creating a search page with several filters using an IonSelect for each. The problem came when I added a 'clear all' button to clear the filters, which threw me into a neverending loop. 😱

My solution

1) Imported the useState Hook and declared a state variable like the one below.

const [isResetting, setIsResetting] = useState(false)
Enter fullscreen mode Exit fullscreen mode

2) Created a reset button which would change the state variable to true when clicked.

onClick={() => setIsResetting(true)}
Enter fullscreen mode Exit fullscreen mode

3) Imported the useEffect hook and set it to run only when isResetting changes. What I wanted to achieve here was for the resetAllFilters function (step 4) to run only when isResetting is set to true.

useEffect(() => {
    if (isResetting) resetAllFilters();
}, [isResetting])
Enter fullscreen mode Exit fullscreen mode

4) Created the resetAllFilters function, which should change the value of all the filters. The last line on this function should be to change the state variable isResetting back to false.

const resetAllFilters = async () => {
    // insert your code 
    setIsResetting(false);
}
Enter fullscreen mode Exit fullscreen mode

5) Last but not least, I made sure that when the state variable isResetting is set to true the IonSelect does not change its value, thereby avoiding going into an infinite loop.

<IonSelect
    multiple={true}
    placeholder="Select tags"
    value={filters.tags}
    placeholder="Select tags"
    onIonChange={e => isResetting ? console.log("reset at work") : applyFilter("tags", e.detail.value)}                                     >

Enter fullscreen mode Exit fullscreen mode

And voila! With these 5 steps I solved my problem at work.

I didn't find any other solutions online, but would love to hear if anyone else has encounted this problem and solved it in a different way.


If you liked what you read hit that ❤️ on the left or wherever it is. If you really liked it don’t forget to share it with the community by hitting that dot-dot-dot icon near the heart.

💻 article.close()

Top comments (0)