Open In App
Related Articles

How to fetch data from an API in ReactJS ?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

Fetching data from an API in ReactJS is a common and crucial task in modern web development. Fetching data from API helps in getting real-time updates dynamically and efficiently. API provides on-demand data as required rather than loading all data. It can be done by using the methods listed below.

Steps to create the React application:

Step 1: Create React Project 

npm create-react-app myreactapp

Step 2: Change your directory and enter your main folder charting as

cd myreactapp

Step 3: Write code in App.js to fetch data from API and we are using the fetch function.

Project Structure of Fetch Data:

Screenshot-from-2023-10-06-09-44-29

Approach 1: Using JavaScript fetch() method

For the data, we have used the API endpoint from http://jsonplaceholder.typicode.com/users we have created the component in App.js and styling component in App.css. From the API we have target “id”, “name”, “username”, and “email”  and fetch the data from API endpoints. We will use the fetch method to get the data from API. Below is the stepwise implementation of how we fetch the data from an API in React. We will use the fetch function to get the data from the API.

Example: This example implements the above mentioned approach.

Javascript

// App.js
import React from "react";
import "./App.css";
class App extends React.Component {
    // Constructor
    constructor(props) {
        super(props);
 
        this.state = {
            items: [],
            DataisLoaded: false,
        };
    }
 
    // ComponentDidMount is used to
    // execute the code
    componentDidMount() {
            .then((res) => res.json())
            .then((json) => {
                this.setState({
                    items: json,
                    DataisLoaded: true,
                });
            });
    }
    render() {
        const { DataisLoaded, items } = this.state;
        if (!DataisLoaded)
            return (
                <div>
                    <h1> Pleses wait some time.... </h1>
                </div>
            );
 
        return (
            <div className="App">
                <h1 className="geeks">GeeksforGeeks</h1>
                <h3>Fetch data from an api in react</h3>
                <div className="container">
                    {items.map((item) => (
                        <div className="item">
                            <ol key={item.id}>
                                <div>
                                    <strong>
                                        {"User_Name: "}
                                    </strong>
                                    {item.username},
                                </div>
                                <div>
                                    Full_Name: {item.name},
                                </div>
                                <div>
                                    User_Email: {item.email}
                                </div>
                            </ol>
                        </div>
                    ))}
                </div>
            </div>
        );
    }
}
 
export default App;

                    

CSS

/* App.css*/
.App {
    text-align: center;
    /* color: Green; */
}
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}
 
.item {
    min-width: 33rem;
    text-align: left;
}
 
.geeks {
    color: green;
}

                    

Step to run the application:

Open the terminal and type the following command.  

npm start

Output: Open the browser and our project is shown in the URL http://localhost:3000/

Peek-2023-10-05-17-33

Approach 2: Using axios library

Axios is a Promise based JavaScript Library use to make the http request from the browser. We will use axios.get method to fetch the data from the given api and then present it on the web pages as required using react jsx components.

Steps to install axios:

npm i axios

Example: This example uses axios to get the data from the api and represent on the web page.

Javascript

// App.js
import React from "react";
import "./App.css";
import axios from "axios"; // uimport axios
class App extends React.Component {
    // Constructor
    constructor(props) {
        super(props);
        this.state = {
            items: [],
            DataisLoaded: false,
        };
    }
 
    // ComponentDidMount is used to
    // execute the code
    componentDidMount() {
        axios.get(
                "https://jsonplaceholder.typicode.com/users"
            )
            .then((res) => {
                this.setState({
                    items: res.data,
                    DataisLoaded: true,
                });
            });
    }
    render() {
        const { DataisLoaded, items } = this.state;
        if (!DataisLoaded)
            return (
                <div>
                    <h1> Pleses wait some time.... </h1>
                </div>
            );
 
        return (
            <div className="App">
                <h1 className="geeks">GeeksforGeeks</h1>
                <h3>Fetch data from an api in react</h3>
                <div className="container">
                    {items.map((item) => (
                        <div className="item">
                            <ol key={item.id}>
                                <div>
                                    <strong>
                                        {"User_Name: "}
                                    </strong>
                                    {item.username},
                                </div>
                                <div>
                                    Full_Name: {item.name},
                                </div>
                                <div>
                                    User_Email: {item.email}
                                </div>
                            </ol>
                        </div>
                    ))}
                </div>
            </div>
        );
    }
}
 
export default App;

                    

CSS

/* App.css*/
.App {
    text-align: center;
    /* color: Green; */
}
.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
}
 
.item {
    min-width: 33rem;
    text-align: left;
}
 
.geeks {
    color: green;
}

                    

Steps to run the application:

npm start

Output: This output will be visible on http://localhost:3000/

Peek-2023-10-05-17-33

Last Updated : 09 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads