Automatically Refetching Data with React Query
Illustrate the setup for automatic data refetching on window focus or at regular intervals using React Query, ensuring fresh data.
import { QueryClient, QueryClientProvider } from 'react-query';
// Create a client
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: true,
refetchInterval: 10000 // Refetch the data every 10000ms (10 seconds)
}
}
});
Setting up React Query with automatic refetching on window focus and at a regular interval of 10 seconds.
import { useQuery } from 'react-query';
import axios from 'axios';
const fetchData = async () => {
const { data } = await axios.get('https://your-api-endpoint.com/data');
return data;
};
function App() {
const { data } = useQuery('dataKey', fetchData);
// Your component logic and JSX
}
Using the useQuery hook to fetch data with automatic refetching as configured in the QueryClient.