Blog>
Snippets

Handling Error States and Retries with TanStack Config

Provide an example of managing error states and implementing retry logic in a data fetching scenario with TanStack Config.
import { useQuery } from '@tanstack/react-query';
First, import the useQuery hook from TanStack React Query.
const fetchData = async () => {
  // Replace this URL with your API endpoint
  const response = await fetch('https://your-api-endpoint.com/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Define a fetchData function that fetches data from a given endpoint. It throws an error if the response is not OK to handle HTTP errors.
const { data, error, isError, refetch } = useQuery(['dataKey'], fetchData, {
  retry: 3, // Number of retry attempts
  retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000), // Exponential back-off retry delay
  onError: (error) => {
    console.error('Error fetching data:', error.message);
  }
});
Use the useQuery hook to fetch data with the fetchData function. It's configured to retry up to 3 times with an exponential back-off strategy. The onError option logs errors.
if (isError) {
  // Handle the UI when there's an error
  console.log('Retry with refetch:', refetch);
}
Check if there is an error and possibly offer a way to refetch the data manually, for instance, by exposing a button to call refetch function.