Axios

The full project code for the example code listed on this webpage can be downloaded from this link.

Axios is a library that performs the same task as the AJAX fetch() function. Although it is possible to use either Axios or fetch() when working with Node.js, Axios is usually used.

In order to use Axios, we need to install Axios on the command line

npm install axios --save

 

Below are two coding segments that show the comparison between using fetch() and Axios to read a json data file called cars.json.

cars.json

[
    {
        "_id": 0,
        "model": "Avensis",
        "colour": "Red",
        "year": 2020,
        "price": 30000
    },
    {
        "_id": 1,
        "model": "Yaris",
        "colour": "Green",
        "year": 2010,
        "price": 2000
    },
    {
        "_id": 2,
        "model": "Corolla",
        "colour": "Red",
        "year": 2019,
        "price": 20000
    }
]

The code below uses the AJAX fetch() method to read the cars.json data and to use the returned JSON data (await response.json()) to set a component's state property called cars.

    //  Using AJAX fetch()

    async readCarData()
    {
        let url = "json/cars.json"   

        try
        {
            const response = await fetch(url,
            {
                method: `get`,
                headers: {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'},
            })

            this.setState({cars: await response.json()})
        }        
        catch (error)
        {
            console.log('Fetch failed: ', error)
        }
    }

Using Axios, the fetch() code above can be written as:

    //  Using axios

    readCarData() 
    {     
        axios.get("json/cars.json")
        .then(res => {
            console.log(res)
            this.setState({cars: res.data})
        })
    }

"Cars" Worked Example

The full project code for the example code listed on this webpage can be downloaded from this link.

This example places the cars JSON data into a file called cars.json, which is stored in the folder client/public/json/cars.json

Client-Side

client/public/json/cars.json

[
    {
        "_id": 0,
        "model": "Avensis",
        "colour": "Red",
        "year": 2020,
        "price": 30000
    },
    {
        "_id": 1,
        "model": "Yaris",
        "colour": "Green",
        "year": 2010,
        "price": 2000
    },
    {
        "_id": 2,
        "model": "Corolla",
        "colour": "Red",
        "year": 2019,
        "price": 20000
    },
    {
        "_id": 3,
        "model": "Avensis",
        "colour": "Silver",
        "year": 2018,
        "price": 20000
    },
    {
        "_id": 4,
        "model": "Camry",
        "colour": "White",
        "year": 2020,
        "price": 50000
    }
]    

Note that the cars.json file must be held in the client/public folder. Otherwise, the React Component's code will be denied access to it.

client/src/components/DisplayAllCars.js

import React, {Component} from "react"

import axios from "axios"

import CarTable from "./CarTable"


export default class DisplayAllCars extends Component 
{
    constructor(props) 
    {
        super(props)
        
        this.state = {
            cars:[]
        }
    }    


    componentDidMount() 
    { 
        axios.get("json/cars.json")
.then(res =>
{
if(res.data)
{
this.setState({
cars: res.data}) }
else
{
console.log("Records not found") } }) }
render() { return ( <div className="form-container"> <div className="table-container"> <CarTable cars={this.state.cars}/> </div> </div> ) } }

When the component mounts, it reads the data from the file cars.json and use the returned data (res.data) to set the state of the Component's cars property.

    componentDidMount() 
    { 
        axios.get("json/cars.json")
.then(res =>
{
if(res.data)
{
this.setState({
cars: res.data}) }
else
{
console.log("Records not found") } }) }
If there is an error message as a result of a problem with the Axios call, then the error

Server-Side

The Axios library is only called from the client-side. In this example, the cars.json file is also stored on the client-side. Therefore, there are no changes to be made on the server-side.

 
<div align="center"><a href="../versionC/index.html" title="DKIT Lecture notes homepage for Derek O&#39; Reilly, Dundalk Institute of Technology (DKIT), Dundalk, County Louth, Ireland. Copyright Derek O&#39; Reilly, DKIT." target="_parent" style='font-size:0;color:white;background-color:white'>&nbsp;</a></div>