How To Conditionally Display an Algolia Filter using Vue InstantSearch

I needed to conditionally display a filter in Algolia. I was using vue.js to put the UI together for the site. Conditional display of the filter should be an easy thing but apparently Algolia recently removed easy access to the UI state object.

You can find other reported instances of this issue here

The basic idea here is that you should only be able to select a category if we have set post type equal to “post”. Otherwise the category filter should hide away because it is not relevant.

After many attempts to gain access to the UI state in props I finally ended up with success using the following workaround.

<ais-current-refinements :included-attributes="['post_type']">
    <template v-slot="{ items, createURL }">
    <div v-for="item in items" :key="item.attribute">
        <div
            v-for="refinement in item.refinements"
            :key="[
            refinement.attribute,
            refinement.type,
            refinement.value,
            refinement.operator
            ].join(':')"
        >
            <template v-if="refinement.label == 'post'">
                <div class="choose-block">
                    <label for="category">Category:</label>
                    <ais-menu-select attribute="display_category"></ais-menu-select>
                </div>
            </template>
        </div>
    </div>
</template>
</ais-current-refinements>

You have to wrap your filter that should be conditional in a <ais-current-refinements> tag and do your v-if inside.

There might be an easier way to accomplish this, but I couldn’t find it in the Algolia docs. Please give me a shout if you know a better way.

Menu