Basic useQuery Hook with Filter Implementation
Demonstrate how to use the useQuery hook to fetch data with a basic text filter, including how to pass filter parameters to the query function and dynamically refetch data based on filter changes.
import React, { useState, useEffect } from 'react';
import { useQuery } from 'react-query';
import axios from 'axios';
First, import React hooks, react-query's useQuery hook, and axios for making API calls.
const fetchData = async (filter) => {
const { data } = await axios.get(`https://api.example.com/data?filter=${filter}`);
return data;
};
Define an asynchronous fetchData function to retrieve data from an API endpoint, applying a filter parameter to the URL.
const FilteredDataComponent = () => {
const [filter, setFilter] = useState('');
const { data, isLoading, isError, refetch } = useQuery(['dataKey', filter], () => fetchData(filter), { enabled: false });
In your component, initialize state for the filter. Use useQuery to fetch data with that filter, but disable automatic fetching by setting 'enabled' to false.
useEffect(() => {
refetch();
}, [filter, refetch]);
Use the useEffect hook to refetch data whenever the filter state changes.
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error fetching data</div>;
Render a loading state and error handling before displaying actual data.
return (
<div>
<input type="text" value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter data..." />
<ul>{data && data.map(item => <li key={item.id}>{item.name}</li>)}</ul>
</div>
);
};
Render a text input for the filter and list the fetched data. Update the filter state on input change to trigger refetching.
export default FilteredDataComponent;
Finally, export the component for use in your application.