ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

Learn How To Use Axios With React For CRUD In 10 Minutes

Learn How To Use Axios With React For CRUD In 10 Minutes
Learn How To Use Axios With React For CRUD In 10 Minutes

In this article, we will be discussing on how to use axios to make api calls in react. We will understand the concepts of axios with some examples. We will be discussing about the concepts of GET, POST, PUT ,DELETE and async, await terms.

What is Axios?

Axios is a promise based HTTP client for the browser and Node.js. It is used to send asynchronous HTTP requests to REST API and perform CRUD operations. It performs POST, GET, PUT and DELETE functions for CRUD operations. It can be used in plane JavaScript or JavaScript frameworks like React or Vue.

How to setup Axios in React Project?

Prerequisites

  • Node installed.
  • An existing react project.
  • A working API endpoint for making requests.
  • Concepts of useState and useEffect react hooks.

Step1: Install axios to the project.

npm install axios 

Step 2: Import axios in the working component.

import axios from 'axios'

Step 3: Perform the required CRUD operation.

Axios React Hooks Example CRUD

Perform a GET Request.

GET request is performed when we want to read the data from the API endpoint. In axios, we use axios.get() to perform GET request. In the example below, we will fetch the data of users and display the list of users from an api endpoint provided by jsonplaceholder . In react, we use useEffect hooks to fetch the api data to avoid multiple api calls at once. we will store the users data using useState here.

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

function Home() {
  const [users , setUsers] = useState([]);
  useEffect(()=>{
    const fetchData = async() => {
      const response = await axios.get("https://jsonplaceholder.typicode.com/users");
      setUsers(response.data)
    }
    fetchData();
  },[])

  return (
    <div>
      <h1>List of Users</h1>
      {users.map(item=>(<li>{item.name}</li>))}
    </div>
  );
}

export default Home;

The reponse looks like:

axios get response
axios react example

Output:

Perform a POST Request.

POST request is performed when we want to create a new data in the API endpoint. In axios, we use axios.post() to perform POST request. In the example below, we will post the data to the api endpoint https://jsonplaceholder.typicode.com/posts. We need to provide data in the format as demanded by the api endpoint. and send that data along with the api url.

import React from "react";
import axios from 'axios';

function Home() {
  const handleSubmit = async(e) => {
    e.preventDefault();
    let data = {
      userId: 1,
      title:"New Post",
      body:"this is a newly added post."
    }
    const response = await axios.post("https://jsonplaceholder.typicode.com/posts",data);
    console.log("response",response) 
  }   

  return (
    <div>
      <button onClick={handleSubmit}>Post</button>
    </div>
  );
}

export default Home;

Response:

Axios react post example

Perform a PUT Request.

PUT request is used for updating a data. The operation syntax is similar to the POST method. Here, we need to provide the updated data and additionally we need to provide the id of data that we are updating in the api.

import React from "react";
import axios from 'axios';

function Home() {
  const handleSubmit = async(e) => {
    e.preventDefault();
    let data = {
      userId: 1,
      title:"New Post updated",
      body:"this is a newly updated post."
    }
    const response = await axios.put("https://jsonplaceholder.typicode.com/posts/1",data);
    console.log("response",response) 
  }   

  return (
    <div>
      <button onClick={handleSubmit}>Update</button>
    </div>
  );
}

export default Home;

Response:

Axios react hook put example

Perform a DELETE Request.

DELETE request is performed when a certain data needs to be deleted. We need to provide the id of that data in the api endpoint.

import React from "react";
import axios from 'axios';

function Home() {
  const handleSubmit = async(e) => {
    e.preventDefault();
    const response = await axios.delete("https://jsonplaceholder.typicode.com/posts/1");
    console.log("response",response) 
  }   

  return (
    <div>
      <button onClick={handleSubmit}>Delete Post 1</button>
    </div>
  );
}

export default Home;

Response:

How to use axios in react for delete request

Async/Await

In the api request functions above, we can see the terms async and await. async ensures that the function returns a promise and wraps non-promises in it. await must be used only inside the async function. It is used to wait for the promise.

Conclusion

In this article, we discussed on how to use axios with react and understand the concepts of performing CRUD operations using axios.

Sign up for daily dose of tech articles at your inbox.
Loading