Blog>
Snippets

Client-Side Error Handling with useEffect

Use the useEffect hook in a Next.js component to handle errors that might occur when fetching data client-side, and show how to display error messages in the UI.
import { useState, useEffect } from 'react';

export default function DataFetchingComponent() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        // Replace with your data fetching logic
        const response = await fetch('https://your-api-endpoint');
        const result = await response.json();
        setData(result);
      } catch (err) {
        setError('An error occurred while fetching data.');
        console.error(err);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      {error && <p className="error-message">{error}</p>}
      {data && <div>{/* Render your data here */}</div>}
    </div>
  );
}
This JavaScript snippet is a Next.js functional component using the useEffect hook to fetch data client-side and handle any errors that might occur. If an error is caught during the fetch operation, the error state is updated, and an error message is displayed in the UI. Replace 'https://your-api-endpoint' with the actual API endpoint you intend to fetch data from. The 'error-message' CSS class can be styled to highlight the error on the page.
.error-message {
  color: red;
  font-weight: bold;
}
This is the accompanying CSS for the error message. It styles the error message in red and bold to make it stand out to the user. Apply this CSS within your global stylesheet or within a style tag specific to the DataFetchingComponent, depending on your project's styling architecture.