• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • GUEST POST
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Guide To Use Axios With React (Free Bonus Code)

Guide To Use Axios With React (Free Bonus Code)

By Sigit Prasetya Nugroho ∙ September 1, 2019 ∙ Javascript ∙ Leave a Comment

Share : TwitterFacebookTelegramWhatsapp

When we build a web applications using the React framework, we can make HTTP requests by utilizing a lightweight library called Axios.

JavaScript has modules that simplify the HTTP request process for sending and receiving data from a restful API. I already discussed in the article tutorial Javascript AJAX. In this article, we will focus on how to use Axios in react apps. watch the following video snippet

Lately, the use of Axios is familiar among Developers, especially Javascript. Axios is known as the Promise based HTTP client where Axios has priority returns promises rather than callbacks.

Actually, to make an HTTP request to the API server is enough using the fetch API. Why do we still need Axios? What is the difference with the fetch API?

Table of Contents

  • 1 Difference between fetch API and AXIOS
  • 2 Axios React Tutorial
    • 2.1 Install Axios React
    • 2.2 GET HTTP Request
    • 2.3 POST HTTP Request
    • 2.4 Axios React ASYNC/AWAIT
    • 2.5 AXIOS Default Data Config
  • 3 Conclusion

Difference between fetch API and AXIOS

Before continuing how to use Axios with react, you should first to know about the difference between the fetch API and Axios

Response value :

Axios returns data as JSON. Unlike fetch API, we must parse the data object into the JSON object using the .json() method.

Handling Error :

To handle errors, Axios execute the catch() function and will not run the .then() function because Axios has a feature: Canceling Requests. This feature will cancel the request if an error occurs the status code (400,401, 404, etc …). Unlike the fetch API, fetch still executes the .then() command when it receives an error with a status code 400,401,404 …

Ok up to this point we already know the advantages of using Axios library. How does it apply axios with react?

Complete Tutorial Axios In React Projects

Axios React Tutorial

In this tutorial, we will use ReactJS (can also be applied to react native Axios)

Install Axios React

The installation is quite easy, you need to run the following command using npm or yarn as explained from the official Axios website.

Run the following command in the root folder of your react projects

1
2
3
4
5
# Yarn
$ yarn add axios
 
# npm
$ npm install axios --save

To use Axios, we import it with the following code

1
import axios from 'axios';

GET HTTP Request

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Postlist extends Component{
    state = {
        post : {},
        detailUser : {},
        asyncData : {},
        inputname : ''
    }
getDetailUser(userId){
         axios.get('https://jsonplaceholder.typicode.com/users/'+userId)
        .then(response =>{
            console.log(response.data);
             this.setState({
                detailUser : response.data
            })
        }).catch(err => {
            alert("Error get detail user : "+err)
        })
    }
 
componentDidMount(){
        axios.get('https://jsonplaceholder.typicode.com/posts/1')
        .then(response =>{
            console.log(response);
            this.setState({
                post : response.data
            })
        })
}
render(){
return(
        <div>
            <h2>GET HTTP REQUEST</h2>
            <p> Title : {this.state.post.title}</p>
            <p> Content : {this.state.post.body}</p>
            <button onClick={this.getDetailUser.bind(this,1)}>Detail Author</button>
            <div>
                {  Object.entries(this.state.detailUser).length !== 0 && this.state.detailUser.constructor === Object &&
                    <div>
                        <p>Name : {this.state.detailUser.name}</p>
                        <p>Email : {this.state.detailUser.email}</p>
                        <p>Phone : {this.state.detailUser.phone}</p>
                        <p>Website : {this.state.detailUser.website}</p>
                    </div>
                }
            </div>
</div>
)
}
}

Explanation:

– Why do we must call the API in componentDidMount lifecycle hook?

As I quoted from https://daveceddia.com

  • Using componentDidMount() explains if the data will be loaded after the rendering process is done. So, we can manage the initial state and not cause an error.
  • Using componentDidMount() ensures that API calls are only made once from the client-side.
  • Using axios.get() will get a promise of returning data in JSON object form.

– Information on axios response data includes config, data, headers, requests, status, statustext.

– Using the try-catch method is the best way to handle errors when accessing the API in Axios.

POST HTTP Request

The difference when making POST Request, we add data properties to be sent to the server.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React,{Component} from 'react';
import axios from 'axios';
 
class Postlist extends Component{
    state = {
        post : {},
        detailUser : {},
        asyncData : {},
        inputname : ''
    }
    handleChange = event => {
        this.setState({ inputname: event.target.value });
    }
    
    postSubmit = event => {
        event.preventDefault();
         const user = {
          name: this.state.inputname
        };
    
        axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
          .then(res => {
            console.log(res);
            console.log(res.data);
          })
    }
 
  
render(){
    return(
        <div>
          
            <h2>POST HTTP  REQUEST</h2>
            <div>
                <form onSubmit={this.postSubmit}>
                    <label>
                        New Name:
                        <input type="text" name="name" onChange={this.handleChange} />
                    </label>
                    <button type="submit">Submit User</button>
                </form>
            </div>
            
        </div>
    )
}
}
 
export default Postlist;

Explanation:

– When the input value changed, the onChange() event will execute the “handlechange” function to add the data to the state.

– When the submit button clicked, reactjs will execute the post request in postSubmit function.

– The data’s sent is a JSON object.

Because Axios uses Promises, we can make many requests at once using async-await.

Axios React ASYNC/AWAIT

Async/await is a feature that has been present since ES2017. This feature makes it easier for us to handle the asynchronous processes. To understand async/await, you should first understand the Promise (please read Tutorial Javascript Asynchronous, Callbacks ,and Promise).

1
2
3
4
async function test(){
result = await doAsync()
console.log(result)
}

Explanation :

  • Async : change function to asynchronous.
  • Await : this function will suspend the next execution until the asynchronous process is complete, from the above example code it means that console.log(result) will not to be executed before the doAsync() function process is completed.

Await can be used for many times in a function.

Example async/await in Axios react

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import React,{Component} from 'react';
import axios from 'axios';
 
class Postlist extends Component{
    state = {
        post : {},
        detailUser : {},
        asyncData : {},
        inputname : ''
    }
    async allData(){
         try{
            const getPost = await axios.get("https://jsonplaceholder.typicode.com/posts/2");
            this.setState({
                asyncData : {
                    title : getPost.data.title,
                    content : getPost.data.body
                }
            })
            console.log(getPost);
            const getUser = await  axios.get('https://jsonplaceholder.typicode.com/users/'+getPost.data.userId)
            console.log(getUser);
            let objuser = this.state.asyncData;
            objuser.name = getUser.data.name;
            objuser.email = getUser.data.email
            this.setState({
                asyncData : objuser  
            })
        } catch(error) {
            alert("error" + error)            
        }
    }
  
render(){
    return(
        <div>
            
            <h2>ASYNC - AWAIT</h2>
            <button onClick={this.allData.bind(this)}>Reload Data</button>
            <p><strong>Title</strong> : {this.state.asyncData.title}</p>
            <p><strong>Content</strong> : {this.state.asyncData.content}</p>
            <p><strong>Author</strong> : {this.state.asyncData.name}</p>
            <p><strong>Email</strong> : {this.state.asyncData.email}</p>
        </div>
    )
}
}
 
export default Postlist;

Explanation :

– To make many API requests in sequence, it is mandatory to use try-catch to handling errors.

– Axios will make a request to retrieve the data post.

– After getting the post data, then use the post result, namely post.userId to make requests to retrieve the user’s detail.

AXIOS Default Data Config

One of the advantages of Axios is that it allows us to do initial or default configurations such as baseUrl, headers so that it speeds up application creation.

How to make the Axios with react instance

1
2
3
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

The Complete Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import React,{Component} from 'react';
import axios from 'axios';
 
class Postlist extends Component{
    state = {
        post : {},
        detailUser : {},
        asyncData : {},
        inputname : ''
    }
    async allData(){
         try{
            const getPost = await axios.get("https://jsonplaceholder.typicode.com/posts/2");
            this.setState({
                asyncData : {
                    title : getPost.data.title,
                    content : getPost.data.body
                }
            })
            console.log(getPost);
            const getUser = await  axios.get('https://jsonplaceholder.typicode.com/users/'+getPost.data.userId)
            console.log(getUser);
            let objuser = this.state.asyncData;
            objuser.name = getUser.data.name;
            objuser.email = getUser.data.email
            this.setState({
                asyncData : objuser  
            })
        } catch(error) {
            alert("error" + error)            
        }
    }
    getDetailUser(userId){
         axios.get('https://jsonplaceholder.typicode.com/users/'+userId)
        .then(response =>{
            console.log(response.data);
             this.setState({
                detailUser : response.data
            })
        }).catch(err => {
            alert("Error get detail user : "+err)
        })
    }
 
    handleChange = event => {
        this.setState({ inputname: event.target.value });
    }
    
    postSubmit = event => {
        event.preventDefault();
         const user = {
          name: this.state.inputname
        };
    
        axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
          .then(res => {
            console.log(res);
            console.log(res.data);
          })
    }
 
    componentDidMount(){
        axios.get('https://jsonplaceholder.typicode.com/posts/1')
        .then(response =>{
            console.log(response);
            this.setState({
                post : response.data
            })
        })
    }
render(){
    return(
        <div>
            <h2>GET HTTP REQUEST</h2>
            <p> Title : {this.state.post.title}</p>
            <p> Content : {this.state.post.body}</p>
            <button onClick={this.getDetailUser.bind(this,1)}>Detail Author</button>
            <div>
                {  Object.entries(this.state.detailUser).length !== 0 && this.state.detailUser.constructor === Object &&
                    <div>
                        <p>Name : {this.state.detailUser.name}</p>
                        <p>Email : {this.state.detailUser.email}</p>
                        <p>Phone : {this.state.detailUser.phone}</p>
                        <p>Website : {this.state.detailUser.website}</p>
                    </div>
                }
            </div>
            <hr/>
            <h2>POST HTTP  REQUEST</h2>
            <div>
                <form onSubmit={this.postSubmit}>
                    <label>
                        New Name:
                        <input type="text" name="name" onChange={this.handleChange} />
                    </label>
                    <button type="submit">Submit User</button>
                </form>
            </div>
            <hr/>
            <h2>ASYNC - AWAIT</h2>
            <button onClick={this.allData.bind(this)}>Reload Data</button>
            <p><strong>Title</strong> : {this.state.asyncData.title}</p>
            <p><strong>Content</strong> : {this.state.asyncData.content}</p>
            <p><strong>Author</strong> : {this.state.asyncData.name}</p>
            <p><strong>Email</strong> : {this.state.asyncData.email}</p>
        </div>
    )
}
}
 
export default Postlist;

The above result like the following gif image below

Tutorial Axios With React And Bonus Code

Conclusion

Axios is one of the necessary tools to use when you build large React app.

Async/Await is a function that is very helpful in handling Promise Objects, especially on values or objects returned by Axios that bring the response from the server.

Hopefully, this Axios react tutorial helps you to understand the API handling on react.

Another Javascript Related Post :

  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)
  • The Right Way Understanding React Lifecycle For Beginners

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Leave a Reply Cancel reply

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

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (7) Publisher Tips (5) react (3) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) widget (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com