Dynamic default refinement for custom menu

Hi,

I have create a react instant search custom menu and it works fine.

<CustomMenu
attribute=“menuType”
defaultRefinement=“Apple”
transformItems={items => items.sort(sortMenuItems)}
/>

I can set a default refinement as a string. It’s working fine. My question is if I have like 3 menu types [‘Apple’, ‘Samsung’, ‘Huawei’] I want to set menu type on availability of the records.
Example: If I don’t have any results for ‘Apple’, I need to fall back to ‘Samsung’ as my default menu selection.

Is this possible? Can somebody please show me an example for this kind of application. Thanks in advance.

Regards,

Nethanjan.

Hi @nethanjana,

This behavior is not possible out-of-the-box, but it’s possible to implement it. Note that it won’t be possible to pick a value from the records for the fallback. If the initial search returns no results, we can’t pick the value from the records. The list of fallback must be hard-coded client side.

Will it work for your use case? If it’s a yes, we can take a look at how we can implement that in a follow-up message.

Hope that helps!

Hi @samuel

Thanks for the reply. Yes I can arrange a hard coded list of fallback, we have some predefined menu types.
For an example let’s say that we have some hard coded item types [‘Apple’, ‘Samsung’, ‘Huawei’]. And my default refinement is ‘Apple’. Now user visit the site and search for ‘Galaxy’ and there are no galaxy results for type ‘Apple’, so how we can arrange that follow-up message?

Regards,
Nethanjan

Hi @nethanjana,

I see two solutions: one with optionalFilters, one with InstantSearch.

The optionalFilters lets you provide a list of filters to rank the results. With this filter rather than returning no results the search will rank first the Apple products, then Samsung then Huawei. You can find more information about that in the documentation. With React InstantSearch you can apply those filters statically with configure. If they are dynamic you have to create your widget that will apply them.

The alternative with InstantSearch is to rely on stateResults to detect a search without results. If it happens you can manually alter the searchState to update the filter value from Apple → Samsung → Huawei. You can leverage the “control mode” of InstantSearch to manually update the state (the guide is about URL but the concept about the control mode remains the same). Unfortunately, this solution will count one more request at each retry. Here is what it could look like in pseudo-code:

Hope that helps!