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
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?
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
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.
Leave a Reply