Implementing dynamic filters with React Query
Show how to dynamically alter query keys based on user-selected filters to re-fetch data that meets certain criteria from an API using React Query.
import { useQuery } from 'react-query';
import axios from 'axios';
First, import useQuery from React Query and axios for making API calls.
const fetchFilteredData = async (filters) => {
const queryString = Object.keys(filters)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(filters[key])}`)
.join('&');
const { data } = await axios.get(`/api/data?${queryString}`);
return data;
};
Define an async function to fetch data. It takes filters object as argument, converts it to a query string, and uses axios to make a GET request to the API.
const FiltersComponent = ({ filters }) => {
const { data, error, isLoading } = useQuery(
['filteredData', filters],
() => fetchFilteredData(filters),
{ keepPreviousData: true }
);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error occurred</div>;
return (
<div>{data && data.map(item => <div key={item.id}>{item.name}</div>)}</div>
);
};
This React component uses the useQuery hook to fetch filtered data. The query key is an array where the first element is a fixed string and the second element is the dynamic filters object. The fetchFilteredData function is called with filters as the argument. keepPreviousData option is set to true to keep displaying the current data until the new data is loaded.