Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Use Axios with ReactJS ?).
In this article, we will understand how to use Axios with ReactJS. Many projects on the web need to interface with a REST API at some stage in their development. Axios is a lightweight HTTP client based on the $http
service within Angular.js v1.x and is similar to the native JavaScript Fetch API. In this article, we will see examples of how to use Axios to access the popular JSON Placeholder API within a React application.
A famous quote about learning is :
” Change is the end result of all true learning.”
So Let’s begin.
Introduction
Axios is promise-based, which gives you the ability to take advantage of JavaScript’s async
and await
for more readable asynchronous code.
We can also intercept and cancel requests, and there’s built-in client-side protection against cross-site request forgery.
Prerequisites
To follow along with this article, we’ll need the following:
- Node.js version 10.16.0 installed on our computer.
- A new React project set up with Create React App.
- It will also help to have a basic understanding of JavaScript along with a basic knowledge of HTML and CSS.
Steps to Use Axios library
Step 1 – Adding Axios to the Project
In this section, we will add Axios to the axios-tutorial
React project. To add Axios to the project, open our terminal and change directories into our project:
$ cd axios-tutorial
Then run this command to install Axios:
$ npm install axios
Next, we will need to import Axios into the file we want to use it in.
Step 2 – Making a GET
Request
In this example, we create a new component and import Axios into it to send a GET
request.
Inside the src
folder of our React project, create a new component named PersonList.js
:
src/PersonList.js
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
persons: []
}
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const persons = res.data;
this.setState({ persons });
})
}
render() {
return (
<ul>
{ this.state.persons.map(person => <li>{person.name}</li>)}
</ul>
)
}
}
First, we import React and Axios so that both can be used in the component. Then we hook into the componentDidMount
lifecycle hook and perform a GET
request.
We use axios.get(url)
with a URL from an API endpoint to get a promise which returns a response object. Inside the response object, there is data that is then assigned the value of person
.
We can also get other information about the request, such as the status code under res.status
or more information inside of res.request
.
Step 3 – Making a POST
Request
In this step, we will use Axios with another HTTP request method called POST
.
Remove the previous code in PersonList
and add the following to create a form that allows for user input and subsequently POST
s the content to an API:
src/PersonList.js
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
name: '',
}
handleChange = event => {
this.setState({ name: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
const user = {
name: this.state.name
};
axios.post(`https://jsonplaceholder.typicode.com/users`, { user })
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Person Name:
<input type="text" name="name" onChange={this.handleChange} />
</label>
<button type="submit">Add</button>
</form>
</div>
)
}
}
Inside the handleSubmit
function, we prevent the default action of the form. Then update the state
to the user
input.
Using POST
gives us the same response object with information that we can use inside of a then
call.
To complete the POST
request, we first capture the user
input. Then we add the input along with the POST
request, which will give us a response. We can then console.log
the response, which should show the user
input in the form.
Step 4 – Making a DELETE
Request
In this example, we will see how to delete items from an API using axios.delete
and passing a URL as a parameter.
Change the code for the form from the POST
example to delete a user instead of adding a new one:
src/PersonList.js
import React from 'react';
import axios from 'axios';
export default class PersonList extends React.Component {
state = {
id: '',
}
handleChange = event => {
this.setState({ id: event.target.value });
}
handleSubmit = event => {
event.preventDefault();
axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
<label>
Person ID:
<input type="text" name="id" onChange={this.handleChange} />
</label>
<button type="submit">Delete</button>
</form>
</div>
)
}
}
Again, the res
object provides us with information about the request. We can then console.log
that information again after the form is submitted.
Step 5 – Using a Base Instance in Axios
In this example, we will see how we can set up a base instance in which we can define a URL and any other configuration elements.
Create a separate file named api.js
. Export a new axios
instance with these defaults:
src/api.js
import axios from 'axios';
export default axios.create({
baseURL: `http://jsonplaceholder.typicode.com/`
});
Once the default instance is set up, it can then be used inside of the PersonList
component. We import the new instance like this:
src/PersonList.js
import React from 'react';
import axios from 'axios';
import API from '../api';
export default class PersonList extends React.Component {
handleSubmit = event => {
event.preventDefault();
API.delete(`users/${this.state.id}`)
.then(res => {
console.log(res);
console.log(res.data);
})
}
}
Because http://jsonplaceholder.typicode.com/
is now the base URL, we no longer need to type out the whole URL each time we want to hit a different endpoint on the API.
Step 6 – Using async
and await
In this example, we will see how we can use async
and await
to work with promises.
The await
keyword resolves the promise
and returns the value
. The value
can then be assigned to a variable.
handleSubmit = async event => {
event.preventDefault();
//
const response = await API.delete(`users/${this.state.id}`);
console.log(response);
console.log(response.data);
};
In this code sample, the .then()
is replaced. The promise
is resolved, and the value is stored inside the response
variable.
That’s all about in this article.
Conclusion
In this article, We understood how to use Axios with ReactJS. We explored several examples on how to use Axios inside a React application to create HTTP requests and handle responses.
Thanks for reading ! I hope you enjoyed and learned about the Axios library usage in ReactJS. Reading is one thing, but the only way to master it is to do it yourself.
Please follow and subscribe to the blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.
You can find Other articles of CoolmonkTechie as below link :
You can also follow official website and tutorials of React as below links :
If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.
Thanks again Reading. HAPPY READING!!???
Hello there, I discovered your blog by the use of Google at the same time as searching for a related matter, your web site got here up, it seems to be good. I’ve bookmarked it in my google bookmarks.