HTTP Requests with axios in ReactJS


In this article, we are going to learn how to send and receive Http Responses with axios in a React application.

Why Use axios?

  • Automatic conversion of response to JSON format

  • Easy to use and more secure

  • Setting up global HTTP interceptors

  • Simultaneous Request

Installing the module

npm install axios

OR

yarn add axios

Npm is the node package manager which manages our React package but yarn is the more secure, faster and lightweight package manager.

Sending GET request

https://jsonplaceholder.typicode.com/todos/1

Jsonplaceholder is a fake API which is used to learn the process of the sending requests.

Example

App.jsx

import React, { useEffect, useState } from 'react';
const App = () => {
   const [data, setData] = useState(null);
   const [fetchData, setFetch] = useState(false);

   useEffect(() => {
      if (fetchData) {
         axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then((res) => setData(res.data.title));
      }
   }, [fetchData]);
   return (
      <>
         <h1>{data}</h1>
         <button onClick={() => setFetch(true)}>Fetch Data</button>
      </>
   );
};
export default App;

In the above example, we are sending the GET request to the jsonplaceholder and accessing the data which is going to be inserted in the state as soon as the response is received.

Response sent by axios

Output

This will produce the following result.

Sending POST request

https://jsonplaceholder.typicode.com/todos/1

Jsonplaceholder is a fake API which is used to learn the process of the sending requests.

Example

App.jsx

import React, { useEffect, useState } from 'react';
import './App.css';
const App = () => {
   const [data, setData] = useState(null);
   const [val, setVal] = useState('');
   const [fetchData, setFetch] = useState(false);

   useEffect(() => {
      if (fetchData) {
         const payload = {
            method: 'POST',
            body: JSON.stringify({ title: val }),
         };
         axios.post('https://jsonplaceholder.typicode.com/posts', payload)
.then((res) => setData(res.data.id));
      }
   }, [fetchData]);
   return (
      <>
         {data && <h1>Your data is saved with Id: {data}</h1>}
         <input
            placeholder="Title of Post"
            value={val}
            onChange={(e) => setVal(e.target.value)}
         />
         <button onClick={() => setFetch(true)}>Save Data</button>
      </>
   );
};
export default App;

In the above example, we are sending the POST request to the jsonplaceholder with the input field value in the body and displaying the response accordingly.

Response sent by axios

Output

This will produce the following result.

Updated on: 18-Mar-2021

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements