Blog>
Snippets

Handling Errors in TanStack Ranger

Present a code example to handle errors gracefully in TanStack Ranger when performing asynchronous data fetching in a React app.
import { useQuery } from '@tanstack/react-query';
Import useQuery hook from TanStack Query for data fetching.
const fetchData = async () => {
  // Fetch data from an API
  const response = await fetch('https://example.com/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Define an async function to fetch data from an API, throwing an error if the response is not OK.
const { data, error, isLoading, isError } = useQuery(['dataKey'], fetchData);
Use the useQuery hook to fetch data. Provide a unique key and the fetchData function. It returns the data, error state, loading state, and error state.
if (isLoading) return <div>Loading...</div>;
Check if the query is in loading state and show a loading indicator.
if (isError) return <div>An error occurred: {error.message}</div>;
Check if the query resulted in an error and display the error message.
<div>{JSON.stringify(data)}</div>
Render the fetched data as a string if there is no error and the data is loaded.