Mastering CRUD Operations with Axios: A Complete Guide

Mastering CRUD Operations with Axios: A Complete Guide

Learn how to perform Create, Read, Update, and Delete operations using Axios, the popular JavaScript library for making HTTP requests.

Axios

It's a popular JavaScript library that allows us to make HTTP requests from our Web App. It can be used in the browser as well as in the Node.js environment.

Why Choose Axios Over Fetch:-

  • More features: Axios provides more features out of the box than the fetch API, such as the ability to perform cancellable requests, transform request and response data, and set default headers.

  • Easier error handling: Axios has a built-in mechanism for handling errors, making it easier to catch and handle error responses from the server.

  • Browser compatibility: Axios is compatible with a wider range of browsers than the fetch API, as it includes polyfills for older browsers.

  • Convenience: Axios provides a simpler and more convenient API for making HTTP requests, with fewer boilerplate code required than the fetch API.

  • Interceptors: Axios also provides interceptors, which allow you to modify requests or responses globally before they are sent or received, which can be useful for things like authentication or logging.

Steps to use Axios

  1. First, we need to install it using any package manager.

     npm install axios
    
  2. Import Axios into the jsx/js file where we want to use it.

     import axios from 'axios';
    
  3. Next, we need to create a function to make an API call.

     function dataFetching() {
       axios.get('https://api.example.com/data')
         .then(response => {
           // handle success
           console.log(response.data);
         })
         .catch(error => {
           // handle error
           console.log(error);
         })
     }
    
  4. Next, we need to call the function dataFetching() in our component. The code of the component will look as follows.

     function App() {
       const [data, setData] = useState([]);
    
       useEffect(() => {
         dataFetching();
       }, []);
    
       function dataFetching() {
         axios.get('https://api.example.com/data')
           .then(response => {
             setData(response.data);
           })
           .catch(error => {
             console.log(error);
           })
       }
    
       return (
         <div className="app">
             <ul>
             {data.map(item => (
               <li key={item.id}>{item.name}</li>
             ))}
             </ul>
         </div>
       );
     }
    

    In the above code, we are using the useState hook to create a state variable data that holds the fetched data. We are then mapping over the data array to render a list of items using the map function. Each item is rendered as an <li> element with the name property displayed as the text. We are using the key property to ensure each item is unique.

    Note: The code assumes the API response returns an array of objects with an id and name property.

CRUD Operations Using Axios

We have already seen how to Read data from an API using Axios. Now, let's see how to use Axios to create, update and delete entries.

The first two steps remain the same but now we need to create a different function for each different task, i.e, Adding, Updating and Deleting Data using API.

Function To Add Data (Create Operation)

function addData() {
    axios.post('https://api.example.com/data', newData)
      .then(response => {
        setData([...data, response.data]);
        setNewData({ name: '' });
      })
      .catch(error => {
        console.log(error);
      })
  }

We first send a POST request to the API with the newData object as the data payload. If the request is successful, the API returns the newly added data object as a response. We then update our local state data by appending the new data object to the existing array of data objects using the spread operator. Finally, we reset the newData state variable to an empty object, so that the input field for adding new data is cleared.

Function To Update Data

function updateData() {
    axios.put(`https://api.example.com/data/${selectedData.id}`, selectedData)
      .then(response => {
        const newData = data.map(item => {
          if (item.id === selectedData.id) {
            return response.data;
          }
          return item;
        });
        setData(newData);
        setSelectedData(null);
      })
      .catch(error => {
        console.log(error);
      })
  }

We first send a PUT request to the API with the selectedData object as the data payload. If the request is successful, the API returns the updated data object as a response. We then update our local state data by replacing the old data object with the new one using the map method. We find the data object to replace by comparing the IDs of each object. Finally, we reset the selectedData state variable to null, so that the edit form is no longer displayed.

Function To Delete Data

function deleteData(id) {
    axios.delete(`https://api.example.com/data/${id}`)
      .then(() => {
        const newData = data.filter(item => item.id !== id);
        setData(newData);
      })
      .catch(error => {
        console.log(error);
      })
  }

We first send a DELETE request to the API with the ID of the data object to be deleted as part of the URL. If the request is successful, the API does not return a response body. We then update our local state data by filtering out the deleted data object using the filter method. We find the data object to delete by comparing the IDs of each object. Finally, we reset the selectedData state variable to null, so that the edit form is no longer displayed.

Note: We used the catch method in all the above examples to handle any errors that may occur during the request, and log them to the console. This can help with debugging if something goes wrong with the API request.

Now, let's add these functions to the component that we made earlier and do some changes to the UI to add, update, and delete these items using forms and form inputs.

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

function MyComponent() {
  const [data, setData] = useState([]);
  const [newData, setNewData] = useState({ name: '' });
  const [selectedData, setSelectedData] = useState(null);

  useEffect(() => {
    fetchData();
  }, []);

  function fetchData() {
    axios.get('https://api.example.com/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.log(error);
      })
  }

  function addData() {
    axios.post('https://api.example.com/data', newData)
      .then(response => {
        setData([...data, response.data]);
        setNewData({ name: '' });
      })
      .catch(error => {
        console.log(error);
      })
  }

  function updateData() {
    axios.put(`https://api.example.com/data/${selectedData.id}`,selectedData)
      .then(response => {
        const newData = data.map(item => {
          if (item.id === selectedData.id) {
            return response.data;
          }
          return item;
        });
        setData(newData);
        setSelectedData(null);
      })
      .catch(error => {
        console.log(error);
      })
  }

  function deleteData(id) {
    axios.delete(`https://api.example.com/data/${id}`)
      .then(() => {
        const newData = data.filter(item => item.id !== id);
        setData(newData);
      })
      .catch(error => {
        console.log(error);
      })
  }

  function handleInputChange(event) {
    setNewData({ ...newData, [event.target.name]: event.target.value });
  }

  function handleEdit(item) {
    setSelectedData(item);
  }

  function handleCancel() {
    setSelectedData(null);
  }

  return (
    <div>
      <h1>Data List</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>
            {item.name}
            <button onClick={() => handleEdit(item)}>Edit</button>
            <button onClick={() => deleteData(item.id)}>Delete</button>
          </li>
        ))}
      </ul>
      {selectedData && (
        <div>
          <h2>Edit Data</h2>
          <form onSubmit={updateData}>
            <label>
              Name:
              <input type="text" name="name" value={selectedData.name} onChange={(event) => setSelectedData({ ...selectedData, name: event.target.value })} />
            </label>
            <button type="submit">Save</button>
            <button onClick={handleCancel}>Cancel</button>
          </form>
        </div>
      )}
      <div>
        <h2>Add Data</h2>
        <form onSubmit={addData}>
          <label>
            Name:
            <input type="text" name="name" value={newData.name} onChange={handleInputChange} />
          </label>
          <button type="submit">Add Data</button>
        </form>
      </div>
    </div>
  );
}

We've added a new state variable selectedData to hold the data for the item being edited. We've also added the functions handleCancel and handleEdit.

The handleEdit function is called when the user submits the edit form. It is responsible for updating the selectedData state variable with the new values from the form, and then calling the updateData function to send the updated data to the API.

The handleCancel function is called when the user cancels the edit form. It is responsible for resetting the selectedData state variable to null, so that the edit form is no longer displayed.