CRUD With API In React | asadmukhtar.info
Step-by-Step Guide to Setting Up Authentication in Laravel 12 with Breeze   |   Manual Authentication in Laravel 12: Step-by-Step Guide   |   How to Build a REST API in Laravel 12 with Sanctum   |   Laravel 12 CRUD Application with Image Upload   |   Laravel 12 Multi-Auth System: Admin & User Login   |   How to Integrate Stripe Payment Gateway in Laravel 12   |   Building a Role-Based Access Control (RBAC) in Laravel 12   |   How to Use Laravel 12 Queues and Jobs for Background Tasks   |   Laravel 12 Livewire CRUD Example with Validation   |   Email Verification and Password Reset in Laravel 12   |   How to Use Laravel 12 API with Vue.js 3   |   Laravel 12 AJAX CRUD with jQuery and Bootstrap   |   Laravel 12 Multi-Language Website Setup   |   React Best Practices for 2025: Performance, SEO, and Scalability   |   How to Build a Full-Stack MERN App: A Step-by-Step Guide   |   React State Management: Redux vs. Context API vs. Recoil   |   Server-Side Rendering (SSR) in React with Next.js for SEO   |   How to Optimize React Apps for Faster Load Times   |   Building a REST API with Node.js and Express for a React App   |   Integrating JWT Authentication in React and Node.js (MERN Stack)   |   Real-time Chat App with React, Node.js, and Socket.io   |   How to Deploy a MERN Stack Application on AWS or Vercel   |   Connecting React Frontend to a Node.js Backend with Axios   |   Laravel Implement Flash Messages Example   |   How to integrate Angular 19 with Node.js and Express for full-stack development   |   Best practices for connecting Angular 19 frontend with Laravel API   |   Step-by-step guide to upgrading an existing project to Angular 19   |   How to implement authentication in Angular 19 using JWT and Firebase   |   Optimizing server-side rendering in Angular 19 with route-level render modes   |   Using Angular 19 signals for state management in large applications   |   How to create standalone components in Angular 19 for modular architecture   |   Building a CRUD application in Angular 19 with MongoDB and Express   |   Implementing lazy loading in Angular 19 to improve performance   |   How to integrate Angular 19 with GraphQL for efficient data fetching   |   Vue 3 Composition API vs Options API: A Comprehensive Comparison   |   Fetching and Displaying Data from APIs in Vue.js with Axios   |   Building a Todo App in Vue.js with Local Storage Integration   |   Handling Forms and Validation in Vue.js Using VeeValidate   |   State Management in Vue.js Applications Using Vuex   |   10 Most Important Tasks Every MERN Stack Developer Should Master   |   How to Build a Full-Stack CRUD App with MERN Stack   |   Best Practices for Authentication & Authorization in MERN Stack   |   1. MEAN Stack vs. MERN Stack: Which One Should You Choose in 2025   |   Top 10 Node.js Best Practices for Scalable and Secure Applications   |   How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)   |   Mastering Angular and Express.js for Full-Stack Web Development   |   Top 10 Daily Tasks Every Frontend Developer Should Practice   |   Essential Backend Development Tasks to Boost Your Coding Skills   |   Real-World Mini Projects for Practicing React.js Daily   |   Laravel Developer Task List: Beginner to Advanced Challenges   |   How to Assign Effective Tasks to Your Intern Developers   |   10 Must-Try Tasks to Master JavaScript Fundamentals   |   Practical CSS Challenges That Improve Your UI Design Skills   |   Top Tasks to Learn API Integration in React and Angular   |   Best Task Ideas for a 30-Day Web Development Challenge   |   Top Git and GitHub Tasks Every Developer Should Know   |   30-Day Task Plan for Web Development Interns   |   Weekly Task Schedule for Junior Developers in a Startup   |   How to Track Progress with Development Tasks for Interns   |   What Tasks Should You Give to Interns in a MERN Stack Project   |   Build These 5 Projects to Master React Routing   |   Task-Based Learning: Become a Full-Stack Developer in 90 Days   |   Daily Coding Tasks That Will Sharpen Your Logical Thinking   |   Top 7 Backend Task Ideas to Practice With Node.js and MongoDB   |  

1. What is CRUD?

CRUD operations are the basic functions for managing data:

  • Create: Adding new data (e.g., adding a new user).
  • Read: Retrieving existing data (e.g., fetching a list of users).
  • Update: Modifying existing data (e.g., editing a user's information).
  • Delete: Removing data (e.g., deleting a user).

2. Set Up a Simple API

For this example, we will use JSONPlaceholder, a free online REST API for testing and prototyping. It provides endpoints for users and other data, which is perfect for demonstrating CRUD operations.

The base URL for JSONPlaceholder is:

https://jsonplaceholder.typicode.com

3. Install Axios

To make API requests in React, we'll use Axios, a promise-based HTTP client.

npm install axios

4. Implementing CRUD in React

Let’s break down how to handle each CRUD operation.

Step 1: Set Up Your React Component

We’ll begin by setting up the initial React component where we'll manage our API requests.

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

function CrudExample() {
  const [users, setUsers] = useState([]);
  const [newUser, setNewUser] = useState({ name: "", email: "" });
  const [editUser, setEditUser] = useState({ id: "", name: "", email: "" });

  const apiUrl = "https://jsonplaceholder.typicode.com/users";

  // Fetching data from API (Read)
  useEffect(() => {
    axios.get(apiUrl)
      .then((response) => setUsers(response.data))
      .catch((error) => console.error(error));
  }, []);

  // Creating a new user (Create)
  const createUser = () => {
    axios.post(apiUrl, newUser)
      .then((response) => setUsers([...users, response.data]))
      .catch((error) => console.error(error));
  };

  // Updating user details (Update)
  const updateUser = () => {
    axios.put(`${apiUrl}/${editUser.id}`, editUser)
      .then((response) => {
        const updatedUsers = users.map((user) =>
          user.id === response.data.id ? response.data : user
        );
        setUsers(updatedUsers);
      })
      .catch((error) => console.error(error));
  };

  // Deleting a user (Delete)
  const deleteUser = (id) => {
    axios.delete(`${apiUrl}/${id}`)
      .then(() => {
        setUsers(users.filter((user) => user.id !== id));
      })
      .catch((error) => console.error(error));
  };

  return (
    <div>
      <h1>CRUD with API in React</h1>

      {/* Display users */}
      <h2>Users List</h2>
      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.name} ({user.email})
            <button onClick={() => deleteUser(user.id)}>Delete</button>
            <button onClick={() => setEditUser(user)}>Edit</button>
          </li>
        ))}
      </ul>

      {/* Create new user form */}
      <h2>Create User</h2>
      <input
        type="text"
        placeholder="Name"
        value={newUser.name}
        onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
      />
      <input
        type="email"
        placeholder="Email"
        value={newUser.email}
        onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
      />
      <button onClick={createUser}>Add User</button>

      {/* Edit user form */}
      {editUser.id && (
        <div>
          <h2>Edit User</h2>
          <input
            type="text"
            value={editUser.name}
            onChange={(e) => setEditUser({ ...editUser, name: e.target.value })}
          />
          <input
            type="email"
            value={editUser.email}
            onChange={(e) => setEditUser({ ...editUser, email: e.target.value })}
          />
          <button onClick={updateUser}>Update User</button>
        </div>
      )}
    </div>
  );
}

export default CrudExample;

5. Explanation of CRUD Operations

Create User

  • createUser function uses POST to send new data to the API.
  • When the user is added successfully, the state is updated with the new user.

Read Users

  • useEffect is used to fetch data from the API when the component is mounted ([] as a dependency).
  • The axios.get() method retrieves data from the API and updates the users state.

Update User

  • The updateUser function is triggered when you update the user’s information.
  • We use PUT to send the updated data to the API, and once the update is successful, the state is updated with the modified user list.

Delete User

  • The deleteUser function uses DELETE to remove a user from the API.
  • After deletion, the state is updated by removing the user from the users list.

6. Handling Errors and Loading States

It’s always important to handle errors and loading states when working with APIs.

  • You can add a loading state to display a loading message while data is being fetched.
  • Use try-catch blocks or .catch() to handle any errors that occur during API requests.

7. Key Points to Remember

  • Use Axios or fetch to make API calls in React.
  • Use state hooks like useState to store and manage data in your component.
  • useEffect helps to fetch data on component mount and manage side effects.
  • CRUD operations are essential when interacting with RESTful APIs in React.
  • Always handle API errors and loading states to ensure a smooth user experience.

8. Conclusion

Implementing CRUD operations with an API in React is a core skill that enables you to build dynamic web applications. With React hooks like useState and useEffect, managing state and side effects becomes much simpler. By integrating these hooks with Axios or fetch for API requests, you can easily perform Create, Read, Update, and Delete operations, creating interactive and dynamic applications.