DEV Community

Cover image for Using Axios Guide
Christian Cedeno
Christian Cedeno

Posted on • Updated on

Using Axios Guide

Below is a beginner guide on how to install and use Axios in React.js

how to install

using npm:
$ npm install axios

using yarn:
$ yarn add axios

how to import:

import axios from 'axios';

The import must be added to the top of the react component axios is being implemented in.

Axios usage:

Axios is a HTTP client library used in React JS and Vanilla JS to make request to a specified endpoint. These request are known as HTTP request. The request usually made are GET which is known as Read in CRUD, POST is known as Create in CRUD, PATCH is to update in CRUD and lastly DELETE.

HTTP Request Examples

GET Request:


const [post, setPost] = useState([]);
useEffect(() => {
axios.get('url')
.then((response) => {
setPost(response.data);
});
}, []);

POST Request:

function createPost() {
axios.post(baseURL, {
title: "Hello World!",
body: "my latest post."
})
.then((response) => {
setPost(response.data);
});
}

PATCH request:

function updatePost() {
axios.patch(
url/${id}, {
body: "an update of my latest post."
})
.then((response) => {
setPost(response.data);
});
}

DELETE Request:

function deletePost() {
axios.delete(
url/${id})
.then(() => {
alert("Post deleted!");
setPost(null)
});
}

Using async and await:

async-await syntax in axios allows for less code since the .then and .catch callback functions aren't needed.

GET Request with Async-Await

const [post, setPost] = useState([]);
const client = axios.create({
baseURL: "https://jsonplaceholder.typicode.com/posts"
});
useEffect(() => {
async function getPost() {
const response = await client.get("/1");
setPost(response.data);
}
getPost();
}, []);

Why should you consider using axios to make your http request:

Axios have built in crud functions to make request simple.
Ex: axios.get, axios.patch, axios.post, axios.delete.

You'll use less lines of code to make endpoint request since request with axios requires only one .then()

Top comments (0)