Automatic Data Refetching with React Query
Illustrate setting up React Query to automatically refetch data at specified intervals or when certain conditions are met.
import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourComponent />
</QueryClientProvider>
);
}
This code snippet is setting up React Query in your React application. It creates a new instance of QueryClient and uses QueryClientProvider to pass the instance throughout your application, enabling React Query's features in any child component.
import { useQuery } from 'react-query';
const fetchData = async () => {
const response = await fetch('https://your-api-endpoint.com/data');
if (!response.ok) throw new Error('Network response was not ok');
return response.json();
};
const useData = () => useQuery('dataKey', fetchData, { refetchInterval: 20000 });
This code snippet demonstrates how to use React Query's useQuery hook to fetch data and set it to refetch at a specified interval. Here, fetchData is a function that fetches data from a server, and 'dataKey' is a unique key for the query. The option refetchInterval is set to 20000 milliseconds (20 seconds), meaning React Query will automatically refetch the data every 20 seconds.
import { useQuery } from 'react-query';
const fetchData = async () => {/* implementation */};
const useData = () => useQuery('dataKey', fetchData, { refetchOnWindowFocus: true });
This code snippet is an example of setting up a query with React Query that automatically refetches data when the window gains focus. The useQuery hook is used with 'refetchOnWindowFocus' option set to true, ensuring the data is fresh when users come back to your app after focusing on other tasks.