Blog>
Snippets

Handling Asynchronous Data Fetching in Route Components

Illustrate a method for handling asynchronous data fetching within a component rendered by React Router, including loading states and error handling.
import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
Import necessary hooks from React and React Router DOM.
const fetchData = async (url) => {
  try {
    const response = await fetch(url);
    if (!response.ok) throw new Error('Data could not be fetched!');
    return await response.json();
  } catch (error) {
    throw error;
  }
};
Define a function for fetching data asynchronously from a given URL.
function RouteComponent() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const { id } = useParams();
  useEffect(() => {
    fetchData(`/api/data/${id}`)
      .then(data => {
        setData(data);
        setLoading(false);
      })
      .catch(error => {
        setError(error.message);
        setLoading(false);
      });
  }, [id]);
Create a functional component that uses the useState and useEffect hooks from React to fetch data based on the URL parameter 'id'.
if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error}</div>;
  return (
    <div>
      <h1>Data Details</h1>
      <p>{JSON.stringify(data)}</p>
    </div>
  );
}
Add conditional rendering inside the component to handle loading and error states, and display data once it's fetched.
export default RouteComponent;
Export the component for use in your application.