How to fetch API data in ReactJS ?

11 / Nov / 2022 by Milan Chourasia 0 comments

We can fetch data by using the Javascript fetch() method. The Fetch API is a new standard to server requests with Promises, it also includes additional features. This blog will help you understand the implementation of fetch API in both functional and class components by walking through each one with sample code. Let’s start –

Consider the below object as a sample response from API:

{
data: [
{ "title": "Di", "date": "22 Oct 2022" },
{ "title": "Diii", "date": "23 Oct 2022" }
]
}

For Functional Component:

Below are the simple steps –

Step 1
Import useState & useEffect

Step 2
define state variables to store the API response using useState method.

Step 3
In the last step, call the API in the useEffect method.

Below is an example:

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

const App = () => {
const [data, setData] = useState([]);
useEffect(() => {
    fetch("https://apidata.com")
      .then(res => res.json())
      .then(
        (result) => {
          setData(result);
        }
      )
}, []);
return (
    <div className=”list”>
    {data.map((item,index) => (
        <div key={index}>
        {item.title} {item.date}
        </div>
    ))}
    </div>
);
};
export default App;

For Class Component:

Step 1
Import Component

Step 2
define state inside the class constructor

Step 3
In the last step call the API inside componentDidMount method.

Below is an example:

import React, { Component } from "react";

class App extends Component {
    constructor(props) {
      super(props);
      this.state = {
        data: []
      };
    }
     componentDidMount() {
      fetch("https://apidata.com")
        .then(res => res.json())
        .then(
            (result) => {
            this.setState({
                data: result.data
            });
            }
        )
    }
    render() {
      const { data } = this.state;
      return (
        <div className=”list”>
          {data.map((item,index) => (
            <div key={index}>
              {item.title} {item.date}
            </div>
          ))}
        </div>
      );
    }
  }
  export default App;
FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *