DEV Community

Kamran Ahmad
Kamran Ahmad

Posted on • Edited on

How To fetch data from an API in a React application

To fetch data from an API in a React application, you can use the fetch() function, which is a built-in JavaScript function for making network requests. Here's an example of how you might use fetch() to retrieve data from an API and store it in a React component:

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

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://my-api.com/endpoint');
      const data = await response.json();
      setData(data);
    }
    fetchData();
  }, []);

  return (
    <div>
      {data && (
        <div>
          {data.map(item => (
            <div key={item.id}>{item.name}</div>
          ))}
        </div>
      )}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this example, we're using the useEffect() hook to perform the fetch operation when the component mounts. The useEffect() hook is called with a function that contains the fetch() call, and an empty array as the second argument, which tells React to only call the function when the component mounts.

Once the data is fetched, it is stored in the component's state using the useState() hook, and the component renders the data by mapping over it and rendering each item as a div.

Top comments (0)