Serverspace Black Friday
BM
November 9, 2022
Updated June 7, 2023

How to use Axios in React

Node.js VPS

Introduction

It is one of the most popular and available request-based http request clients, and it is used everywhere, whether in JavaScript or node js.

Aoxis is promise-based, thus with every request, we will get a response from the request object.

Requests can be intercepted and canceled, and there is built-in protection against cross-site spoofing on the client side.

In this publication you will see how Axios requests work in React, using examples you can test the requests on your own server.

What the library can do

  • Using XML queries
  • Using http requests from node.js
  • Supports the Promise API. Promises are much easier to work with because we get the message back anyway
  • Intercepts requests and responses
  • Cancels requests if you need
  • Automatically converts to JSON, it helps to avoid wasting time compiling
  • Supports client side protection against XSFR

What is required

  • Your server has a version of Node.js higher than 10.17.xx installed
  • Your pre-built React project
  • Your project has the axios library installed

Adding Axios to your project

Create or go to your project.

npx create-react-app your-project

The most popular way is to install it using the npm package manager.

npm install axios

Import Aoxis into your project where you want to use it.

Creating a POST request

You will need to create a new UserAdd.js component in your project.

Enter code for the Post request in your UserAdd.js file that will allow the user to enter data and send the API.

nano /mnt/c/Project/UserAdd.js

Try running a POST request using the example and it will add the user.

const axios = require('axios');
axios
.post('https://myfakeapi.com/api/users/', {
firstName: 'Boris',
lastName: 'Moore'
}) // Using a post request, specifying the user
.then((response) => { // Data retrieval and processing
console.log(response.data);})
.catch((error) => { // If the query fails, an error will be displayed on the terminal.
console.error(error);});

Check that the code works, resulting in a promise from the server.

2axios

Creating a GET request

It is required to create a new component under any name, in our case we will use the name CarList. This component must be placed in the directory /mnt/c/Project/. This subdirectory won't be in the mnt directory initially, so it must be created as well.

mkdir /mnt/c/Project/

Go to our newly created CarList document using any text editor of your choice.

nano /mnt/c/Project/CarList

Try performing a Get query using the example and you will get a list of Mitsubishi cars.

const axios = require('axios');
axios.get('https://myfakeapi.com/api/cars/name/Mitsubishi') //Returning pledges using a get-query
.then((response) => { // Data retrieval and processing
console.log(response.data);})
.catch((error) => { // If the query fails, an error will be displayed on the terminal.
console.error(error);});

As a result, we get a list of data from the server thanks to promises.

admin-ajax

Creating a Delete request

You will need to create a new PostRemove.js component in your project.

nano /mnt/c/Project/PostRemove.js

Try performing a DELETE query using the example, it will delete the post.

componentDidMount() {
axios.delete(`https://reqres.in/api/posts/1`)
.then(() => this.setState({ status: 'Delete successful' }));
}

Using a base instance in Axios

This example requires you to create a new api.js component.

nano /mnt/c/Project/myapi.js

By creating this component, we specify a standard link for our server to receive and send requests.

import axios from 'axios';
export default axios.create({
baseURL: `http://yourapiurl.com/`
});

The CarList.js component will be used for testing.

import React from 'react';
import axios from 'axios';
import Api from '/mnt/c/Project/api';
export default class CarList extends React.Component {
\\ . . .
componentDidMount() {
Api.get(`curl --location --request GET 'api/cars/name/Mitsubishi'`)
.then(res => {
const cars = res.data;
this.setState({ cars });
})}\\

After creating an api component, we don't need to constantly specify a link to the server to receive and send requests. You only need to change the path to the desired request in the desired component.

Using async and await

The CarList.js component will be used for testing.

The keyword await allows communication and sends the result in response. The value can be assigned to a variable.

import API from '/mnt/c/Project/api';
export default class CarList extends React.Component {
componentDidMount() {
const response = await Api.get(`curl --location --request GET 'api/cars/name/Mitsubishi'`)
console.log(response);
console.log(response.data);})}

In the example we substitute .then() instead the received data will be displayed in the console. The promise will be fulfilled and the value will be stored inside the variable of the received response.

Check

Before checking the queries, check whether you have the queries specified in the program component.

In our instruction, we will be editing the yourapp.js component.

import CarList from './components/CarList.js';
import PostRemove from './components/PostRemove.js';
import UserAdd. from './components/UserAdd.js';
function App() {
return (
<div ClassName="App">
<CarList/>
<UserAdd/>
<PostRemove/>
</div>)}

Handling query errors

One of the important aspects of handling data we receive from the server is that we can only retrieve it if there are no errors when running the request. To display errors you can use the catch function.

catch (error) { // error handling and displaying in the console
console.log("error get", error);}

If you get an error while executing the query, this function will print the error to the console.

Conclusion

The positive aspects of the Axios library is its ability to automatically convert to JSON, we don't need to do extra manipulation to convert an object to JSON because we will get it in the response. Passing parameters to query, when we execute a method we can pass certain parameters to our query.
In this publication we have deconstructed axios library queries, how they work together with React.

 

Vote:
4 out of 5
Аverage rating : 4.7
Rated by: 3
1101 CT Amsterdam The Netherlands, Herikerbergweg 292
+31 20 262-58-98
700 300
ITGLOBAL.COM NL
700 300
We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.