I need to create a search and filtering functionality that filters and displays only the searched results from the RTK query cached data, and when the user remove the filter, it should show all the cached data. What is the best way to do this?
I thought of creating a local state variable, updating the cached data in the local state variable, and displaying the data using the state. While filtering, I use the filtering logic and update the state variable with the returned value from the filtering function, Is this the correct approach, or is there any other way we can do it using RTK queries?
There are several options available to you to filter the fetched/queried data.
Make the Server do the heavy lifting
If your API endpoints support query parameters it's optimal to make the more powerful backend server do any sorting/filtering. Pass along in the requests how you want response data filtered/sorted/etc.
Example:
export const api = createApi({
reducerPath: 'api',
baseQuery: fetchBaseQuery({ baseUrl: 'https://my.domain.co/api/' }),
endpoints: (builder) => ({
getData: builder.query({
query: ({ options }) => `getdata?key=${options.key}&sortBy=${options.sortBy}`,
}),
}),
})
const { data } = useGetDataQuery({
options: {
key: "someKey",
sortBy: "date",
}
});
Filter in the frontend using useQuery
hook's selectFromResult
const { data } = useGetDataQuery(undefined, {
selectFromResults: ({ data }) => ({
data: data?.filter(....).sort(....);
}),
});
Filter inline in the frontend when rendering
const { data } = useGetDataQuery();
...
return (
...
{data?
.filter(....)
.sort(....)
.map(....)
}
...
);
or memoized
const { data: rawData } = useGetDataQuery();
const data = React.useMemo(() => rawData?
.filter(....)
.sort(....),
[rawData, /* filter value, sortBy value, etc */]
);
...
return (
...
{data?.map(....)}
...
);