javascriptreactjsalgoliareact-instantsearch

React InstantSearch RefinementList transformItems not working


So I have successfully implemented the React InstantSearch library in my app, and am trying to apply a filter to the refinement list (to ensure the filters that show up are relevant to the active user, and hide the ones that aren't). I have tried the below:

<RefinementList attributeName="organization" transformItems={items => items.filter(e => refineList.indexOf(e)>=0)} />

where refineList is a simple array of strings (i.e. ["A", "B", "C"])

However the RefinementList keeps showing all of the filter options, without having the "transformItems" function applied to it. Would it be that I had misunderstood how the "transformItems" works?

Documentation was quite sparse on this topic, so I'm sure it'd be helpful for many other users of the library.


Solution

  • The transformItems function has one parameter: items. It expects in return to have it back.

    items is an array of objects with the following shape:

    {
      label: string,
      value: array<string>,
      count: number,
      isRefined: bool,
    }
    

    To remove a refinement based on an array of strings you can do this:

    const refineList = ['A', 'B'];
    <RefinementList
        attributeName="organization"
        transformItems={items => items.filter(e => 
            refineList.indexOf(e.label) >= 0)}
    />