Correct way to remove dependent filters in the Interaction Manager


#1

Hi Guys, in my React app, I have a visualization that shows packages shipped to a specific US zip code. To narrow down the data, what I’m doing is first selecting a State, then a County, and finally a Zip code, and then displaying the number of packages shipped to that Zip code.

Now in the Interaction Manager I have the three filters of course, and what I need to do is when I remove the County filter, the Zip Code filter is removed as well, or if I remove the State filter, the filters County and Zip Code are removed as well.

What I did was subscribe to the filter:before-remove event of the IM and in the associated function I did the following:

im.on('filter:before-remove', onBeforeRemoveFilter);
const onBeforeRemoveFilter = (data) => {
    const isRemovingState = data.filters.find(
        (f) => f.getLabel() === 'State'
    );
    const isRemovingCounty = data.filters.find(
        (f) => f.getLabel() === 'County'
    );

    const countyFilter = api.getFilters()
        .find((f) => f.getLabel() === 'County');

    const zipFilter = api.getFilters()
        .find((f) => f.getLabel() === 'Zip');

    if (isRemovingState) {
        if (zipFilter) {
            api.removeFilter(zipFilter);
        }
        if (countyFilter) {
            api.removeFilter(countyFilter);
        }
    } else if (isRemovingCounty) {
        if (zipFilter) {
            api.removeFilter(zipFilter);
        }
    }
};

This code works, but the problem is that every time I remove one of the dependent filters api.removeFilter(zipFilter); or api.removeFilter(countyFilter); the IM fires this event again and unnecessarily enters to execute the function onBeforeRemoveFilter again.

Is there any way to avoid this behavior?


#2

Hi @moshdev, yes, if you do it that way you will have multiple entries to the onBeforeRemoveFilter function for each filter you remove manually.

The best practice to achieve what you want is to use the restrictions property of the IM to establish a dependency between the filters. So what you need to do is remove that im.on('filter:before-remove', onBeforeRemoveFilter); subscription and add the following:

const restrictions = [
   { filter: 'County', dependsOn: 'State' },
   { filter: 'Zip', dependsOn: 'County' }
];

.set('restrictions', restrictions)

With this configuration, when removing a filter, the IM will automatically remove its dependencies.

Let me know if you have any other questions about it


#3

Hi @juan.dominguez, thanks for your detailed answer, I tried and it works like a charm. Thanks!