Use of async await  in ReactJs useEffect

Use of async await in ReactJs useEffect

Let's consider a real-time example of using useEffect for fetching data from an API.

import React, { useState, useEffect } from 'react';

function DataFetchingExample() {
  // State variables
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // useEffect for data fetching
  useEffect(() => {
    // Function to fetch data from an API
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    // Call the fetchData function
    fetchData();
  }, []); // Empty dependency array means this effect runs once after the initial render

  // Render based on data fetching status
  if (loading) {
    return <p>Loading...</p>;
  }

  if (error) {
    return <p>Error: {error.message}</p>;
  }

  return (
    <div>
      <h1>Data from API</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default DataFetchingExample;

In this example:

  • We have a component DataFetchingExample that fetches data from an API using the fetch function inside the useEffect.

  • The loading, error, and data states are used to manage the different states of the data fetching process.

  • The component initially renders a loading message while the data is being fetched. If an error occurs, it displays an error message. If the data is successfully fetched, it displays the data.

Conclusion:

This is a simplified example, but it illustrates how useEffect can be used to manage the asynchronous nature of data fetching in React components. The effect runs once after the initial render, fetches data, and updates the component's state accordingly.

Did you find this article valuable?

Support LingarajTechhub by becoming a sponsor. Any amount is appreciated!