DEV Community

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

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay