Blog>
Snippets

Setting Query Timeouts

Demonstrate how to set a timeout for a query in React Query, automatically cancelling the query if it exceeds the specified time limit, and handling the timeout with a custom error message to the user.
import { useQuery } from 'react-query';
import axios from 'axios';
Imports the useQuery hook from React Query and axios for making HTTP requests.
const fetchWithTimeout = (url, timeout = 10000) => {
    const controller = new AbortController();
    const id = setTimeout(() => controller.abort(), timeout);
    return axios.get(url, { signal: controller.signal })
        .finally(() => clearTimeout(id));
};
Defines a function that fetches data with a timeout. The timeout is configurable but defaults to 10000 milliseconds (10 seconds). It uses an AbortController to cancel the fetch if it exceeds the specified timeout.
const useDataWithTimeout = (key, url) => {
    return useQuery(key, () => fetchWithTimeout(url), {
        onError: (error) => {
            if (error.name === 'AbortError') {
                alert('The request timed out. Please try again.');
            } else {
                alert('An error occurred. Please try again later.');
            }
        }
    });
};
Uses the useQuery hook to fetch data with a timeout. It passes the key and URL to the fetchWithTimeout function. If an error occurs, it checks if the error is an AbortError (indicating a timeout) and displays an appropriate message to the user.