Friday, July 5, 2024
HomeLanguagesReactAxios in React: A Guide for Beginners

Axios in React: A Guide for Beginners

In the tech industry, React has emerged as one of the most popular front-end frameworks. However, integrating React with backend languages poses its own challenges. Developers need to adhere to specific rules and write custom code to establish communication with databases. In React, backend communication is typically achieved using the HTTP protocol. While many developers are familiar with the XML Http Request interface and Fetch API for making HTTP requests, there’s another powerful library called Axios that simplifies the process further.

In this article, we will explore Axios, its prominent features, and how it streamlines backend communication in React. We’ll delve into various use cases where Axios shines, enabling efficient database interactions.

Introduction to Axios: Axios, which is a popular library is mainly used to send asynchronous HTTP requests to REST endpoints. This library is very useful to perform CRUD operations.

  1. This popular library is used to communicate with the backend. Axios supports the Promise API, native to JS ES6.
  2. Using Axios we make API requests in our application. Once the request is made we get the data in Return, and then we use this data in our project. 
  3. This library is very popular among developers. You can check on GitHub and you will find 78k stars on it. 

Before you install Axios your React project app should be ready to install this library. Create a React application following the steps given below…

Step 1: Below is the command to create React app in your project…

npx create-react-app new_files

Step 2: Enter in the directory created in the first step.

cd new_files

Step 3: Install Axios library using the command given below…

npm install axios

Step 4: Once this has been done, you can start the server using the command given below..

npm start

After Axios installation, you can import this library into your file and use it to make an HTTP request. Below is the code snippet of a file where the library is imported at the top.

Javascript




import React from "react";
import axios from "axios";
 
class App extends React.Component {
    state = {
        newfiles: null,
    };
 
    handleFile(e) {
 
        // Getting the files from the input
        let newfiles = e.target.newfiles;
        this.setState({ newfiles });
    }
 
    handleUpload(e) {
        let newfiles = this.state.newfiles;
 
        let formData = new FormData();
 
        // Adding files to the formdata
        formData.append("image", newfiles);
        formData.append("name", "Name");
 
        axios({
 
            // Endpoint to send files
            url: "http://localhost:8080/files",
            method: "POST",
            headers: {
 
                // Add any auth token here
                authorization: "your token comes here",
            },
 
            // Attaching the form data
            data: formData,
        })
 
            // Handle the response from backend here
            .then((res) => { })
 
            // Catch errors if any
            .catch((err) => { });
    }
 
    render() {
        return (
            <div>
                <h1>Select your files</h1>
                <input
                    type="file"
 
                    // To select multiple files
                    multiple="multiple"
                    onChange={(e) => this.handleFile(e)}
                />
                <button onClick={(e) => this.handleUpload(e)}>
                    Send Files
                </button>
            </div>
        );
    }
}
 
export default App;


The above example is just a small code description to showcase how to use Axios in your project. We will discuss multiple methods such as GET, POST, and PUT in Axios in the upcoming section.

Need of Axios in React: As we have discussed that Axios allows you to communicate with the APIs in your React project. The same tasks can also be performed by using AJAX, but Axios provide you more functionality and features and that helps you in building your application quickly. 

Axios is a promise-based library, so you need to implement some promise-based asynchronous HTTP requests. jQuery and AJAX also perform the same job but in React project React handles each and everything in its own virtual DOM, so there is no need to use jQuery at all.     

Below is an example to fetch the customer’s data using Axios…

Javascript




const getCustomersData = () => {
    axios
        .then(data => console.log(data.data))
        .catch(error => console.log(error));
};
getCustomersData();


Now let’s come to the next point and understand how different operations can be performed such as fetching the data or consuming the data using Axios (GET-POST-DELETE).

GET Request with Axios: Create a component MyBlog and hook it into the component DidMount lifecycle. Import the Axios at the top and fetch the data with Get request.

Javascript




import React from 'react';
import axios from 'axios';
export default class MyList extends React.Component {
    state = {
        blogs: []
    }
    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/posts`)
            .then(response => {
                const posts = response.data;
                this.setState({ posts });
            })
    }
    render() {
        return (
            <ul>
                {this.state.posts.map(post => { post.title })}
                </ul>
  )}
 }


Here we are using axios.get (URL) to get a promise that returns a response object. Returned response is assigned to the post’s object. We can also retrieve other information such as status code etc.

POST Request with Axios: Create a new component AddPost for Post requests. This request will add a post to the post list. 

Javascript




import React from 'react';
import axios from 'axios';
export default class AddPost extends React.Component {
    state = {
        postTitle: '',
    }
    handleChange = event => {
        this.setState({ postTitle: event.target.value });
    }
    handleSubmit = event => {
        event.preventDefault();
        const post = {
            postName: this.state.postName
        };
        axios.post(
            `https://jsonplaceholder.typicode.com/posts`, { post })
            .then(res => {
                console.log(res);
                console.log(res.data);
            })
        [Text Wrapping Break]
    }
    render() {
        return (
            <div>
                <form onSubmit="{this.handleSubmit}">
                    <label>
                        Post Name:
                        <input type="text" name="name"
                            onChange="{this.handleChange}" />
                    </label>
                    <button type="submit">Add</button>
                </form>
            </div>
        )
    }
}


In the above code, we have made an HTTP Post request and added a new post to the database. The onChange event triggers the method handleChange() and updates the request when the API request returns the data successfully.

Delete Request With Axios: To send the delete request to the server axios.delete is used. You need to specify two parameters while making this request URL and optional config. 

axios.delete(url, { 
  data: { foo: "bar" }, 
  headers: { "Authorization": "******" } 
}); 

While sending the delete request you will have to set the request body and headers. Use config.data for this purpose. In the above POST request, modify the code as given below…

Javascript




handleSubmit = event => {
    event.preventDefault();
    axios.delete(
        `https://jsonplaceholder.typicode.com/posts/${this.state.postName}`)
        .then(res => {
            console.log(res);
            console.log(res.data);
        })
}


Response Objects in Axios: When you send a request to the server, you receive a response object from the server with the properties given below…

  • data: You receive data from the server in payload form. This data is returned in JSON form and parse back into a JavaScript object to you.
  • status: You get the HTTP code returned from the server.
  • statusText: HTTP status message returned by the server.
  • headers: All the headers are sent back by the server.
  • config: original request configuration.
  • request: actual XMLHttpRequest object.

Error Object: You will get an error object if there will be a problem with the request. Promise will be rejected with an error object with the properties given

  • message: Error message text. 
  • response: Response object (if received). 
  • request: Actual XMLHttpRequest object (when running in a browser). 
  • config: Original request configuration. 

Features of Axios Library

  • JSON data is transformed automatically.
  • It transforms the request and response data.
  • Useful in making HTTP requests from Node.js
  • It makes XMLHttpRequests from the browser.
  • Provide client-side support for protecting against XSRF.
  • Supports promise API.
  • Ability to cancel the request.

Shorthand Methods in Axios: Below are some shorthand methods of Axios…

  • axios.request(config)
  • axios.head(url[, 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

This article explained everything about Axios library. We have discussed some useful operations such as fetching the data, posting the data, updating the data, or deleting the data in Axios. Once you will start working on React, you will have to use this library to communicate with the database server. So it is important to make a practice of it and understand how things work in Axios.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

Dominic Rubhabha Wardslaus
Dominic Rubhabha Wardslaushttps://neveropen.dev
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments