How to use React with Axios library?
Hey reader! 👋 In this blog, I will show you how to use React with Axios. Axios is one of the most popular to make HTTP requests from the browser or any other environment and we will use it with react.
About Axios
Axios is among the most widely used HTTP JavaScript client libraries. It is also based on promise, which integrates well with the present async-await
javascript syntax.
The fact that HTTP APIs are used by the browser and comparatively by Node.js is quite different in contrast to each other, which means it is easy to blend Axios in a comfortable environment. It is mainly used to send an asynchronous HTTP request to Rest endpoints.
This is very useful to perform crud operations. Axios library is well known among developers. Using Axios data fetching is kind of easy because of the adoption and support of the Promise API, and Javascript ES6 syntaxes.
It allows you to communicate with APIs in your react-based projects. The need for Axios is very promising and many asynchronous HTTP requests get easily implemented.
Features of Axios Library
- Axios mainly supports JSON data and it is transformed automatically without explicitly defining it.
- It supports Promise API
- Axios transforms all the request and response data.
- It gives you client-side support which is for protecting against Cross-site request forgery (CSRF)
React with Axios
Create an empty react project and if you don’t know how to create react app check out this blog.
After creating a react-app delete the unnecessary files and make it look like this
If you are using codedamn playground, it automatically builds with required files only, but other than codedamn playground like vscode you need to delete the unnecessary files and keep them like those mentioned in the image.
Remove the code too, and now the react app is empty and will look like this
Note: Axios is a promise-based library, which is implemented by some promise-based requests. React take care of everything in its own virtual DOM, so there is no need to get hands-on using jQuery at all.
Axios
As Axios is special for making requests to some remote servers, we need the server as the server I will use Star Wars API swapping i.e swapi.dev. By clicking on this it will redirect you to the documentation and select any point you need, first of all, we will use people who forget to get all the data we need.
Now our API is ready to use, let’s see how to use Axios along with it
In your terminal, install Axios, you can use npm or you can use yarn
npm install axios
Code language: JavaScript (javascript)
yarn add axios
Code language: JavaScript (javascript)
I will be using yarn to install Axios in my system. As Axios is the remote module we need to install it always. After the installation of Axios in your react application
We need to import Axios and then we call it to get or post or any other type of request then you pass the endpoint URL and it returns a promise, which we can handle with, where we will have data or cache and where we will have errors in the easiest way. Also, we use the async-await approach and handle it as well.
So when we have this library, we need to execute some hooks in the place where we will call to get data so let’s import the useEffect
from react, and now when the application starts we will use useEffect
without the dependencies it will work as a complemented mount it will execute only once when we re-render the component.
import React from "react";
import {useEffect} from "react";
import "./App.css";
function App() {
useEffect(()=>{
},[])
return (
<div className="App">
<div>Codedamn</div>
</div>
);
}
export default App;
Code language: JavaScript (javascript)
API with Axios
Now we need to fetch some data, let’s import Axios from the Axios and inside the, we can execute the next Axios get and put URL as you see
useEffect(()=>{
axios.get('https://swapi.dev/api/people/').then((data)=>{
console.log(data)
})
},[])
Code language: JavaScript (javascript)
Here we are getting the data from the API endpoint this data is a return of a promise, so I have received that data and then console log it to in browser. Inside some data, with it, specific information like an account of how many people we found on the next page and the result of the first 10 people.
Now we need to output this information somehow, in this case, let’s use useState
and this will manage the state of the API request and present it on the browser.
I have used the map()
function to iterate through the array. inside the array, we will show only the name of the people and by doing this, we have performed Axios in react with a good example.
import React from "react";
import {useEffect, useState} from "react";
import axios from 'axios'
import "./App.css";
// this is realted to axios
function App() {
const [people, setPeople] = useState([]);
useEffect(()=>{
axios.get('https://swapi.dev/api/people/').then((data)=>{
setPeople(data.data?.results)
})
},[])
return (
<div className="App">
<div>
{people.length ?(
<>
{people.map((person)=>(
<h1>{person.name}</h1>
))}
</>
): <div>Loading...</div>}
</div>
</div>
);
}
export default App;
Code language: JavaScript (javascript)
the output of the above coder, after fetching the data is shown below:
Async-await approach in Axios
You just need to change them useEffect
and do with it an async
function like this:
useEffect(async()=>{
const data = await axios.get("https://swapi.dev/api/people/");
setPeople(data.data?.results)
},[])
Code language: JavaScript (javascript)
Async await is really good to use because of its promise and less code with the clean code base
Methods in Axios
Axios provides and supports many methods that can help you to fetch the data easily without worrying much. Here are the methods mentioned below:
- axios.request(config)
- axios.get(url, config)
- axios.post(url[, data[, config]])
- axios.put(url[, data[, config]])
- axios.delete(url[, config])
- axios.options(url[, config])
- axios.patch(url[, data[, config]])
Conclusion
Axios is a fantastic option for both your front end and back end because of the aforementioned characteristics as well as additional ones like automated JSON transformations or built-in request cancellation. You can use Axios in many of your react applications which require APIs calls and fetching the data.
Some useful operations such as fetching the data, updating the data, and deleting the data in Axios are easily executable. Once you understand the working of Axios, you can make APIs call by yourself and can communicate with the database server.
Axios is now stable earlier it was in beta so using it doesn’t beneficial but now it is as good as it can be. I hope this blog helps you to understand Axios a lot better. Have great learning!😊
Sharing is caring
Did you like what Anas Khan wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: