Fetch Data from an API in React JS

React JS

Today we are going to explain how to fetch data from an API in React JS. In previous article we have explained about how to implement Read more link in React JS.

This is most important topic in React because React is used to manipulate data after fetch data from an API. In this tutorial we will explain how to fetch data from an API in class component and function component. In class component we have used componentDidMount method while in functional component we have used useEffect hooks to fetch the data from an API. We have already explained componentDidMount and useEffect in React JS.

Firstly we will explain fetch data from an API in class component using componentDidMount method.

Fetch data from an API using componentDidMount

fetchData.js

import React from "react";

class FetchData extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }
    }

    componentDidMount() {
        fetch('https://jsonplaceholder.typicode.com/users')  // dummy API
            .then((response) => response.json())
            .then(userData => this.setState({data: userData}))
            .catch((error) => console.log(error))
    }

    render() {
        const {data} = this.state
        return (
            <div>
                <h2>Fetch data from API using Class Component in React</h2>
                <table border="1" align="center">
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                    </tr>
                    {data.map(user => (
                        <tr>
                            <td>{user.id}</td>
                            <td>{user.name}</td>
                        </tr>
                    ))}
                </table>
            </div>
        )
    }
}

export default FetchData

App.js

import React from 'react';
import './App.css';
import FetchData from "./components/fetchData";

function App() {
  return (
    <div className="App">
      <FetchData />
    </div>
  );
}

export default App;

Output

fetch data from an API using componentDidMount

In the above code we have used componentDidMount method to fetch data from an API. We have used dummy API to get the data.

Fetch data from an API on the button click

If you want to get the data on the button click then then you can see below example.

fetchData.js

import React from "react";
class FetchData extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
        }
    }

    fetchUserData = () => {
        fetch('https://jsonplaceholder.typicode.com/users')  // dummy API
            .then((response) => response.json() )
            .then( userData => this.setState({data: userData}))
            .catch((error) => console.log(error))
    }

    render() {
        const { data } = this.state
        return (
            <div>
                <h2>Fetch data from API using Class Component in React</h2>
                <button onClick={this.fetchUserData}>Load User Data</button>
                {data.length > 0 &&
                    <table border="1" align="center">
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                        </tr>
                        {data.map(user => (
                            <tr>
                                <td>{user.id}</td>
                                <td>{user.name}</td>
                            </tr>
                        ))}
                    </table>
                }
            </div>
        )
    }
}
export default FetchData

In the above code we have get the data on the button click. We have call the fetchUserData function on the button click to fetch data from an API.

App.js

import React from 'react';
import './App.css';
import FetchData from "./components/fetchData";

function App() {
  return (
    <div className="App">
      <FetchData />
    </div>
  );
}

export default App;

Output

fetch data from an API on the button click in react

Fetch data from an API using useEffect hook

Now we will use useEffect hook to fetch the data from an API in React JS.

fetchData.js

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

const FetchData = () => {
    const [data, setData] = useState([]);

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

    if(data){
        return (
            <div>
                <h2>Fetch data from API using useEffect Hooks in React</h2>
                <table border="1" align="center">
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                    </tr>
                    {data.map(user => (
                        <tr>
                            <td>{user.id}</td>
                            <td>{user.name}</td>
                        </tr>
                    ))}
                </table>
            </div>

        )
    }

}

export default FetchData;

App.js

import React from 'react';
import './App.css';
import FetchData from "./components/fetchData";

function App() {
  return (
    <div className="App">
      <FetchData />
    </div>
  );
}

export default App;

In the above code we have used useEffect method to fetch the data from an API.

Output

Fetch data from API using useEffect Hooks in React

Conclusion

So in this article we have explained about how to fetch data from an API in React JS. Using this tutorial anyone can easily understand fetching data from an API using useEffect and componentDidMount method.

If you want to improve this tutorial or find anything wrong/incorrect then please leave a message using below comment box.

1 thought on “Fetch Data from an API in React JS

Leave a Reply

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

sixteen − 8 =