Understanding Axios!!!

Understanding Axios!!!

Axios!!!

Sending requests to a web server is one of the most common things we do on the frontend side of the development. Creating a Facebook page, uploading a new Instagram image, sending a tweet , or logging in and signing uo on an new websites: these scenarios all send requests to a server.

Axios is an open source library that helps us send all these kinds of requests by providing a promise-based HTTP client method called POST.

In this blog we will discuss about axios POST both in vanilla js and in react.

Introduction!!

The axios library make asynchronous HTTP requests to REST endpoints in browsers and Node.js.

Axios is a light weight HTTP client for both Node.js and browser, it gives us the ability to take advantages of await& async.

Axios is also quite to the native Javascript Fetch API. It offers a lot of methods like POST, PUT , PATCH, GET, DELETE, and so on.

Why use Axios?

You might wonder why you should use Axios over the native JavaScript fetch() method. Comparatively, Axios has some advantages over fetch().

First, Axios allows us to work with only one promise(.then()) and with JSON data by default unlike in the Fetch API where we must first convert the request body to a JSON string in the first promise:

// With Fetch
fetch(url)
 .then((response) => response.json())
 .then((data) => console.log(data))
 .catch((error) => console.log(error));

// With Axios
axios.get(url)
 .then((response) => console.log(response))
 .catch((error) => console.log(error));

Secondly, Axios can be used on the client as well as on the server, unlike the Fetch API.

Axios functions are also named to match the HTTP methods. To perform a POST request, you use the .post() method, and so on:

axios.post()   // to perform POST request
axios.get()    // to perform GET request
axios.put()    // to perform PUT request
axios.delete() // to perform DELETE request
axios.patch    // to perform PATCH request

Other reasons to use Axios POST over the Fetch API include the following:

  1. Axios allows canceling requests and requesting timeouts, which fetch() does not allow
  2. Axios has better error handling by throwing a wide range of errors, including network errors
  3. Axios has the ability to intercept HTTP requests
  4. Axios has a wider browser support.

Axios POST in vanilla JavaScript

To use Axios in vanilla JavaScript, we must first add the CDN link in the HTML before using it in the script file. Let’s start by creating two files to use: index.html and index.js:

// index.html

<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <div id="app">
      <h1>Login Account</h1>
      <form action="">
        <label for="email">
          Email
          <input type="email" name="" id="email" />
        </label>
        <label for="password">
          Password
          <input type="password" name="" id="password" />
        </label>
        <button id="btn">Login</button>
      </form>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="index.js"></script>
  </body>
</html>

This HTML file creates a simple login page with two input fields, the email and the password fields, and a login button. At the bottom, just above the index.js link, we added the Axios CDN.

Next, we head over to our index.js file that we created and get the email input, password input, and button elements using their Ids. We can then add an onClick event listener that triggers the function whenever we click the button:

// index.js

const emailInput = document.getElementById("email");
const passwordInput = document.getElementById("password");
const btn = document.getElementById("btn");

btn.addEventListener("click", () => {
  const email = emailInput.value;
  const password = passwordInput.value;

  axios.post("https://reqres.in/api/login", {
      email: email,
      password: password
    })
    .then((response) => {
      console.log(response);
    });
});

Using Axios POST in React

We can now perform the same POST request we just did in the vanilla JavaScript example in React. To use Axios in React, we must install the Axios package using npm or yarn. In your terminal, install Axios by running either of the following commands:

$ npm install axios

$ yarn add axios

With Axios installed, let’s go to our App.js file.

Unlike in vanilla JavaScript, we must first import Axios from the Axios package we installed before using it. Then, in our handleSubmit function, let’s call Axios with the POST method just as we did in the vanilla example:

import React, { useState } from "react";
import axios from "axios";

const App = () => {
  const [data, setData] = useState({
    email: "",
    password: ""
  });

  const handleChange = (e) => {
    const value = e.target.value;
    setData({
      ...data,
      [e.target.name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const userData = {
      email: data.email,
      password: data.password
    };
    axios.post("https://reqres.in/api/login", userData).then((response) => {
      console.log(response.status);
      console.log(response.data.token);
    });
  };

  return (
    <div>
      <h1>Login Account</h1>
      <form onSubmit={handleSubmit}>
        <label htmlFor="email">
          Email
          <input
            type="email"
            name="email"
            value={data.email}
            onChange={handleChange}
          />
        </label>
        <label htmlFor="password">
          Password
          <input
            type="password"
            name="password"
            value={data.password}
            onChange={handleChange}
          />
        </label>
        <button type="submit">Login</button>
      </form>
    </div>
  );
};

The above code is a practical example of where and how we can use the Axios POST call. Let’s look at another example where we create a new user or register as a new user:

// App.js

import React, { useState } from "react";
import './styles.css';
import axios from "axios";

const App = () => {
  const [state, setState] = useState({
    name: "",
    job: ""
  });

  const handleChange = (e) => {
    const value = e.target.value;
    setState({
      ...state,
      [e.target.name]: value
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    const userData = {
      name: state.name,
      job: state.job
    };
    axios.post("https://reqres.in/api/users", userData).then((response) => {
      console.log(response.status);
      console.log(response.data);
    });
  };

  return (
    <div>
      <h1>Register or Create new account</h1>
      <hr />
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">
          Name
          <input
            type="text"
            name="name"
            value={state.name}
            onChange={handleChange}
          />
        </label>
        <label htmlFor="job">
          Job
          <input
            type="text"
            name="job"
            value={state.job}
            onChange={handleChange}
          />
        </label>
        <button type="submit">Register</button>
      </form>
    </div>
  );
}

You can also create a styles.css file and copy the CSS styling below to style the app. It’s nothing fancy, but makes the interface view a bit cooler:

// styles.css

body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  font-family: sans-serif;
}
h1 {
  text-align: center;
  margin-top: 30px;
  margin-bottom: 0px;
}
hr {
  margin-bottom: 30px;
  width: 25%;
  border: 1px solid #palevioletred;
  background-colour: #palevioletred;
}
form {
  border: 1px solid black;
  margin: 0 28%;
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
label {
  width: 80%;
  text-transform: uppercase;
  font-size: 16px;
  font-weight: bold;
}
input {
  display: block;
  margin-bottom: 25px;
  height: 6vh;
  width: 100%;
}
button {
  padding: 10px 30px;
  text-transform: uppercase;
  cursor: pointer;
}

With that, we have our registration app to utilize our POST method.

image.png