Blog>
Snippets

Dynamic Filter Creation with useQuery

Exhibit how to dynamically create filters based on user input or other criteria and use these dynamic filters within the useQuery hook to fetch or refetch data.
const [filters, setFilters] = React.useState({});
Initializes a state object for storing dynamic filters.
const updateFilters = (newFilters) => { setFilters({ ...filters, ...newFilters }); };
Function to update the current filters with new values. It merges existing filters with new ones.
const fetchData = async (filters) => { const query = Object.entries(filters).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join('&'); return axios.get(`/api/data?${query}`).then(res => res.data); };
Defines a function to fetch data. It transforms the filters object into a query string and makes an API call.
const { data, isLoading, error } = useQuery(['dataKey', filters], () => fetchData(filters), { keepPreviousData: true });
Uses the useQuery hook to fetch data. It depends on 'filters' state, so any change in filters triggers refetching. keepPreviousData is used to avoid layout shifts.