Fetching API Data with React.JS using Fetch

In React, we can use both fetch and AJAX to make API calls. However, we usually prefer to use fetch because it is a built-in API in modern browsers and does not require any external libraries.

In this article, we will go over the steps for fetching API data with React.js. Let's get started-

Table of Contents

  1.  Create a Child Component
  2. Import the Necessary Modules to Parent 
  3. Define the useStae and useEffect hook
  4. Render the Child Component

Create a Child Component

First we need to create a child component MyComponent.js that will receive a props of data to render:

MyComponent.js
import React from 'react';

function MyComponent({data}) {
  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.body}</p>
        </div>
      ))}
    </div>
  );
}

export default MyComponent;

Import the necessary modules to Parent

Now, we will import the necessary modules to our App.js component for making API calls. 

App.js
import React, { useState, useEffect } from 'react';

function App() {

  return (
    <div>
      <h1>Fetch Data with React</h1>
    </div>
  );
}

export default App;

Define the state and the useEffect hook

We need to define the state where we will store the API response. We can use the useState hook to define the state. We also need to use the useEffect hook to make the API call and update the state. We will use fetch for making HTTP requests. Here's an example:

App.js
import React, { useState, useEffect } from 'react';

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

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

    return (
        <div>
            <h1>Fetch Data with React</h1>
        </div>
    );
}

export default App;

Here, we fetch data from api and update our data state.

Render the component

Next, we need to render the component in our App.js component and pass the data as props to our MyComponent.js component. We can import and use the child component in our App.js file like this:

App.js
import React, { useState, useEffect } from 'react';
import MyComponent from './MyComponent';

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

    useEffect(() => {
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then(response => response.json())
            .then(data => setData(data));
    }, []);

    return (
        <div>
            <h1>Fetch Data with React</h1>
            <MyComponent data={data} />
        </div>
    );
}

export default App;

This will render the MyComponent in our application and display the fetched data.

That's all for today. Thanks for reading the article.