DEV Community

Cover image for 	
ReactJs Step by Step working with Axios - Demo at jsondev.org
xuanqh
xuanqh

Posted on

ReactJs Step by Step working with Axios - Demo at jsondev.org

Today we learn how to use axios to query json in ReactIs. In this article I provide some basic code samples you have an initial approach to axios.

Install axios:

npm install — save axios

The basic parameters:

url: Path to access the json data you want to be.  
headers: headers request For example 'Content-type', 'Authorization', 'Accept' … params: The query parameters on the url.  
data: The data you want to put in the query  
method: The method of query data. For example POST, GET, PUT … 
Enter fullscreen mode Exit fullscreen mode

Getting start with axios:

Step 1: Import library using axios
import axios from 'axios';

Step 2: Declare config

let url = http://jsondev.org/jsondemo  
let config = {  
    method: 'GET',  
    url: this.state.url_test,  
    headers: headers,  
    params: params,  
    data: data  
};  
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a code using the query axios

axios(config)  
    .then(function (response) {  
        console.log('Send REST Api result: ');  
        let dataResponse = response.data;  
        if (dataResponse != null) {  
            console.log(dataResponse);  
        }  
    })  
    .catch(function (error) {  
        console.log('error request api');  
        console.log('NetworkStatus: ' + error.toString());  

        console.log(error.response);  
        let jsonCallBack = {  
            data: error.toString(),  
            status: 0  
        }  
        component.props.parentCallback(jsonCallBack);  
        let statusText ='';  
        try {  
            statusText = error.response.statusText;  
        }catch (e) {  

        }  
        console.log(error.toString() + ".\n" + statusText);  
    });  
Enter fullscreen mode Exit fullscreen mode

Conclusion:

The article is just the first step for anyone new to learning about Reactjs and axios. Thank you for reading and sharing.

Demo:

http://jsondev.org/

Source codes:

https://github.com/xuanqh/jsoneditoronline.git

Top comments (0)