React  

Mastering Axios in React: A Complete CRUD Example

Introduction

Modern web applications often need to communicate with backend services to fetch, create, update, and delete data. In React applications, one of the most popular libraries used for handling HTTP requests is Axios.

Axios makes it easier to interact with APIs and manage asynchronous data compared to the native fetch() method.

What is Axios?

Axios is a promise-based HTTP client for JavaScript used to communicate with REST APIs from the browser or Node.js environment.

It simplifies API calls and provides several useful features such as:

  • Automatic JSON data transformation

  • Request and response interception

  • Better error handling

  • Simplified syntax for HTTP requests

  • Support for all major HTTP methods

Axios is commonly used in React applications to interact with backend services such as ASP.NET Core Web APIs, Node APIs, or other RESTful services.

Installing Axios

Before using Axios, it must be installed in the React project.

npm install axios

After installation, it can be imported into components where API calls are required.

import axios from "axios";

CRUD Operations Using Axios

CRUD stands for:

  • Create – Add new data

  • Read – Fetch existing data

  • Update – Modify existing data

  • Delete – Remove data

These operations are commonly implemented in applications that manage records such as employees, products, or users.

Fetching Data (Read Operation)

The GET method is used to retrieve data from the backend API.

const fetchEmployee = () => {
 axios.get("http://localhost:5288/api/Employee")
  .then(res => setEmployee(res.data))
  .catch(err => console.log(err));
};

This request retrieves employee data from the API and stores it in the React state.

To automatically load the data when the component renders, the function is called inside the useEffect hook.

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

Adding Data (Create Operation)

The POST method is used to create a new record in the database.

const addEmployee = () => {

 const newEmployee = {
  name: name,
  department: department
 };

 axios.post("http://localhost:5288/api/Employee", newEmployee)
  .then(res => {
   setEmployee([...employee, res.data]);
   setName("");
   setDepartment("");
  })
  .catch(err => console.log(err));
};

This sends the new employee data to the API and updates the UI without reloading the page.

Updating Data (Update Operation)

The PUT method is used to update existing records.

const updateEmployee = () => {

 const updatedEmployee = {
  id: id,
  name: name,
  department: department
 };

 axios.put(`http://localhost:5288/api/Employee/${id}`, updatedEmployee)
  .then(() => {
   fetchEmployee();
   setId(null);
   setName("");
   setDepartment("");
  })
  .catch(err => console.log(err));
};

After updating, the employee list is refreshed to display the latest data.

Deleting Data (Delete Operation)

The DELETE method removes a record from the database.

const deleteEmployee = (id) => {

 axios.delete(`http://localhost:5288/api/Employee/${id}`)
  .then(() => {
   setEmployee(employee.filter(emp => emp.id !== id));
  })
  .catch(err => console.log(err));

};

The UI is immediately updated by filtering out the deleted employee.

Displaying Data in a Grid

The fetched employee data can be displayed using a table.

<tbody>

{employee.map(emp => (

<tr key={emp.id}>
<td>{emp.id}</td>
<td>{emp.name}</td>
<td>{emp.department}</td>

<td>
<button onClick={() => editEmployee(emp)}>Edit</button>
<button onClick={() => deleteEmployee(emp.id)}>Delete</button>
</td>

</tr>

))}

</tbody>

This dynamically renders employee records in a grid format.

Conclusion

Axios provides a clean and efficient way to interact with APIs in React applications. By using Axios with React Hooks like useState and useEffect, developers can easily implement full CRUD functionality.

This approach enables seamless communication between the frontend and backend, allowing applications to manage data dynamically without page reloads.

Implementing Axios for CRUD operations is a fundamental practice in modern web development and is widely used in real-world applications.