Filters: How to get clean names based on ids

169 Views Asked by At

I'm building some overview pages which displays a searched, filtered, sorted and paginated list of a resource (customers, users, contracts etc.). So far I have implemented the search, sorting and pagination features but I'm a bit stuck on the filters.

Via a button on the overview page a sidebar can we opened which will show a form with the possible filters. These filters are resource based and some resource api calls to fetch the options. For example the user overview page has a filter for roles and organisations. The different options for these multi-selects will come from an API as an array of objects where each object will have an id and name/label. The calls are triggered in the form component so no extra API calls are made when the filter sidebar is not opened. (I use axios and Tanstack react-query to make/handle these calls).

When submitting the form, the filters are applied by setting the selected filters in a filters state on the overview page (The function setFilters is being passed as prop to the sidebar). react-query will notice that one of the passed properties has changed and will refetch the list.

At this point the filters state can look something like this:

{
   status: 'active',
   organisation: 'Y6XS28Qj4SjPrZJ5w',
   role: 'cybNVunkMrCyzg1ig'
}

For a better user experience I want to display the active filters directly on the overview page. With a simple loop I can go through the filters state and display the values. Status will have a clean badge but organisation and role will be displayed as an id and not a readable name like in the filters sidebar.

That's where I'm stuck. How can I transform these id's into clean names? Do I have to move the api calls to the overview page and make these unnecessary when the user is not applying any filters or are there other options? Extra information to take in consideration:

  • The filters can be shared using the url so it is possible to open an overview page with active filters

  • How to match a filter to the data of an API call? I'm looking for a dynamic way to get transform the id into a clean name. The above example only has three filters but there will be pages with different and more/less filters.

  • Not all filters work with id's.

1

There are 1 best solutions below

0
On

If you have a useOrganization and useRole hook, I'd use those to translate a single entry. If they have the same structure as the filters endpoint, you can prefill the caches of those queries from the filters sidebar.

This is especially important regarding the sharable urls, because it means you can't rely on the filters having previously been fetched.

If there's no way to fetch for a single organization or role, yes, I think you would have to fetch the filters and use those to translate, even if it means fetching filters earlier, potentially even when the user never opens the filter sidebar.