Blog>
Snippets

Handling Error States in Data Fetching

Provide an example of using the useQuery hook to fetch data, including handling for loading, error, and success states, demonstrating robust error handling in a React component.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchData = async () => {
  const { data } = await axios.get('https://api.example.com/data');
  return data;
};

function DataFetchingComponent() {
  const { data, error, isLoading, isError } = useQuery('dataKey', fetchData);

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error.message}</div>;

  return (
    <div>
      <h3>Data Loaded Successfully</h3>
      {/* Render your data here */}
    </div>
  );
}
This code demonstrates how to use the useQuery hook from react-query to fetch data from an API. It handles loading state, error state, and success state by conditionally rendering different components or messages. The fetchData function is an async function that uses axios to fetch data from a specified URL and returns it. Inside the DataFetchingComponent, the useQuery hook is used to perform the data fetching operation, where 'dataKey' is a unique key for the query which can be used for caching and tracking the query status. The code then uses conditional rendering to display a loading message, an error message, or the successful data loaded message along with the fetched data.