Setting Up Query Timeouts
Provide an example of setting both global and per-query timeouts in React Query to prevent the UI from freezing during long-running data fetch operations.
import { ReactQueryCacheProvider, QueryCache, useQuery } from 'react-query';
// Create a new QueryCache and specify global timeouts
const queryCache = new QueryCache({
defaultConfig: {
queries: {
timeout: 5000 // Global timeout: 5 seconds
}
}
});
const App = () => (
<ReactQueryCacheProvider queryCache={queryCache}>
{/* App content goes here */}
</ReactQueryCacheProvider>
);
This code sets up a global timeout for all queries in React Query. The `QueryCache` is configured with a default timeout of 5 seconds (5000 milliseconds), after which all queries will be automatically cancelled if they have not completed.
const fetchProjects = () => fetch('/api/projects').then(res => res.json());
const Projects = () => {
// Using useQuery with a specific timeout for this query
const { data, error, isFetching } = useQuery('projects', fetchProjects, {
timeout: 10000 // 10 seconds timeout for this query
});
if (error) {
return <div>Error fetching projects</div>;
} else if (isFetching) {
return <div>Loading...</div>;
}
return <div>{JSON.stringify(data)}</div>;
};
This piece of code demonstrates how to set a specific timeout for a single query. Here, the `useQuery` hook is used to fetch project data, with a timeout set to 10 seconds just for this particular query, overriding any global timeout settings.