Blog>
Snippets

Graceful Error Handling in Data Fetching

Showcase handling loading states and errors in the context of TanStack Router, including displaying fallback components during data fetching.
import { createBrowserRouter, RouterProvider, Route } from 'react-router-dom';
import React from 'react';
import { ErrorBoundary } from 'react-error-boundary';
Imports necessary components from 'react-router-dom' and the 'ErrorBoundary' component for handling errors.
function ErrorFallback({error}) {
  return <div>An error occurred: {error.message}</div>;
}
Defines a fallback component that displays an error message.
function DataFetchingComponent() {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState(null);

  React.useEffect(() => {
    fetch('/some-api')
      .then((response) => response.json())
      .then(setData)
      .catch(setError)
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <div>Loading...</div>;
  if (error) throw error;
  return <div>{JSON.stringify(data)}</div>;
}
A component that fetches data from an API, displaying loading and error states appropriately.
const router = createBrowserRouter([
  {
    path: '/',
    element: (
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <DataFetchingComponent />
      </ErrorBoundary>
    ),
  },
]);
Creates a router with a route that uses ErrorBoundary to catch errors from the DataFetchingComponent.
function App() {
  return <RouterProvider router={router} />;
}
Defines the main app component that renders the RouterProvider with the defined router.