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)
2) Created a reset button which would change the state variable to true
when clicked.
onClick={() => setIsResetting(true)}
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])
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);
}
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)} >
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)