how to use axios in 2023

Axios is a popular JavaScript library used for making HTTP requests. It is often used in web applications to interact with APIs or fetch data from a server. In this article, we will explore the use of Axios with real-time examples for GET, PUT, POST, and DELETE requests in a React application.

Real-time Example:

Here we are building a real-time to-do list application. In such an application, we need to constantly update the UI with the latest to-do items added, edited, or deleted by other users. You can achieve this by using Axios to make requests to our server every few seconds and fetch the latest to-do items.

Let's see how we can achieve this using Axios with real-time examples for GET, PUT, POST, and DELETE requests.

Step 1: Set up the Project

To get started, we need to set up a new project. We can use any front-end framework of your choice. In this example, we will use React.

Create a new React project using create-react-app. Open your terminal and run the following commands:

npx create-react-app todo-app
cd todo-app
npm install axios

Step 2: Create a To-Do Component

Create a new component called Todo.js. This component will display the to-do items and allow users to add, edit, and delete items. Here is an example of what the component could look like:

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

function Todo() {
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    const interval = setInterval(() => {
      fetchTodos();
    }, 5000);
    return () => clearInterval(interval);
  }, []);

  const fetchTodos = () => {
    axios.get("/api/todos").then((response) => {
      setTodos(response.data);
    });
  };

  const handleAddTodo = (event) => {
    event.preventDefault();
    const todo = event.target.elements.todo.value;
    axios.post("/api/todos", { text: todo }).then((response) => {
      fetchTodos();
    });
    event.target.elements.todo.value = "";
  };

  const handleEditTodo = (event, id) => {
    event.preventDefault();
    const text = event.target.elements.text.value;
    axios.put(`/api/todos/${id}`, { text: text }).then((response) => {
      fetchTodos();
    });
  };

  const handleDeleteTodo = (id) => {
    axios.delete(`/api/todos/${id}`).then((response) => {
      fetchTodos();
    });
  };

  return (
    <div>
      <form onSubmit={handleAddTodo}>
        <input type="text" name="todo" />
        <button type="submit">Add Todo</button>
      </form>
      {todos.map((todo) => (
        <div key={todo.id}>
          <form onSubmit={(event) => handleEditTodo(event, todo.id)}>
            <input type="text" name="text" defaultValue={todo.text} />
            <button type="submit">Save</button>
          </form>
          <button onClick={() => handleDeleteTodo(todo.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
}

export default Todo;

Here, we are using the useEffect hook to call the fetchTodos function every 5 seconds using setInterval. In the fetchTodos function, we are using Axios to make a GET request to the /api/todos endpoint on our server. When the response is returned, we update the todos state with the new to-do items.