React – Fetch data using Axios

By | 04/11/2020

In this post, we will see how to fetch data in React using a library called Axios, modifying the application created in the post: React – Fetch data in Class component.
Axios is a promise based HTTP client for the browser and Node.js and, it makes easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations.
For knowing all Axios’ functionalities, go to the Official GitHub project.

First of all, we install the library Axios using the command npm I axios and then, we modify the component GetListUsers:


import React, { Component } from 'react'
import ViewListUsers from './HTMLUserList';
import axios from 'axios';

// definition of the Web API's url
const APIUrl = "";

class GetListUsers extends Component {
    // definition of variables
    constructor() {
        this.state = {
          lstUsers: [],
          loading: false,
          error: null,


    // Definition of a method used to load data from service
    // The method is called by the button "Load Data"
            .then(result => this.setState({
                                    loading: false
            .catch(error => this.setState({
                                    error: error,
                                    loading: false
    render() {
        // Using the Destructuring assignment, we define three variables used in the component
        const { lstUsers, loading, error } = this.state;

        // in case of error, component will display an error message
        if (error) {
            return <h1 style = {{color:"white"}}>Attention! There are problems with the Web API.</h1>;

        return (
                <h1 style = {{color:"white"}}>List users</h1>
                <button onClick={() => this.LoadData()}>Load Data</button>
                {loading ? <h2 style = {{color:"white"}}>Loading...</h2>:
                    <ViewListUsers users={lstUsers}/> 

export default GetListUsers

If we run the application, this will be the result:

Leave a Reply

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