CodeGym /Courses /Frontend SELF EN /CRUD Operations

CRUD Operations

Frontend SELF EN
Level 44 , Lesson 1
Available

6.1 Introduction to CRUD

CRUD is an acronym that stands for four main operations you can perform with data: Create (Create), Read (Read), Update (Update) and Delete (Delete). These operations are fundamental for working with databases and form the basis for most web applications.

What is CRUD?

  • Create: The create operation is used to add new records to a database. This lets you enter new data into the system.
  • Read: The read operation is used to retrieve data from the database. It allows users to request and view existing information.
  • Update: The update operation is used to change existing records in the database. This lets you edit and adjust data.
  • Delete: The delete operation is used to remove records from the database. It allows you to delete unnecessary or outdated data.

HTTP Methods for CRUD Operations

In the context of web development, CRUD operations are often performed using HTTP requests to an API. Different HTTP methods correspond to different CRUD operations:

  • POST: used to create new resources.
  • GET: used to read (retrieve) resources.
  • PUT and PATCH: used to update existing resources. PUT is generally used for completely replacing a resource, while PATCH is for partial updates.
  • DELETE: used to delete resources.

Why are CRUD Operations Important?

CRUD operations are the foundation for working with data in web applications. They allow developers to implement key functionalities like creating user accounts, editing profiles, viewing data, and deleting records. These operations also enable interaction between the client and server, allowing for data and command exchange.

Modern Tools for Performing CRUD Operations

Modern web apps often use various tools and libraries to perform CRUD operations via API:

  • Fetch API: A built-in browser way of making HTTP requests, based on Promises.
  • Axios: A popular library for making HTTP requests, offering a convenient and comprehensive API.

These tools help developers easily and efficiently perform CRUD operations, offering flexibility and simplicity in integrating with different server-side APIs.

6.2 Using Fetch

Let's look at using Fetch to perform CRUD operations.

Create:

JavaScript
    
      const createData = async (data) => {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });
        const result = await response.json();
        console.log('Created:', result);
      };

      createData({ title: 'foo', body: 'bar', userId: 1 });
    
  

Read:

JavaScript
    
      const readData = async (id) => {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        const result = await response.json();
        console.log('Read:', result);
      };

      readData(1);
    
  

Update:

JavaScript
    
      const updateData = async (id, data) => {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(data)
        });
        const result = await response.json();
        console.log('Updated:', result);
      };

      updateData(1, { title: 'foo', body: 'bar', userId: 1 });
    
  

Delete:

JavaScript
    
      const deleteData = async (id) => {
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`, {
          method: 'DELETE'
        });
        if (response.ok) {
          console.log('Deleted:', id);
        } else {
          console.error('Failed to delete:', id);
        }
      };

      deleteData(1);
    
  

6.3 Using Axios

Let's look at using Axios to perform CRUD operations.

Create:

JavaScript
    
      const axios = require('axios');

      const createData = async (data) => {
        try {
          const response = await axios.post('https://jsonplaceholder.typicode.com/posts', data);
          console.log('Created:', response.data);
        } catch (error) {
          console.error('Error creating data:', error);
        }
      };

      createData({ title: 'foo', body: 'bar', userId: 1 });
    
  

Read:

JavaScript
    
      const readData = async (id) => {
        try {
          const response = await axios.get(`https://jsonplaceholder.typicode.com/posts/${id}`);
          console.log('Read:', response.data);
        } catch (error) {
          console.error('Error reading data:', error);
        }
      };

      readData(1);
    
  

Update:

JavaScript
    
      const updateData = async (id, data) => {
        try {
          const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, data);
          console.log('Updated:', response.data);
        } catch (error) {
          console.error('Error updating data:', error);
        }
      };

      updateData(1, { title: 'foo', body: 'bar', userId: 1 });
    
  

Delete:

JavaScript
    
      const deleteData = async (id) => {
        try {
          const response = await axios.delete(`https://jsonplaceholder.typicode.com/posts/${id}`);
          if (response.status === 200) {
            console.log('Deleted:', id);
          }
        } catch (error) {
          console.error('Error deleting data:', error);
        }
      };

      deleteData(1);
    
  

6.4 Tips for Using CRUD

Tips for Using CRUD Operations via API:

  1. Error Handling: Always handle potential errors when performing HTTP requests. Use try...catch blocks or catch methods for error handling.
  2. Data Validation: Before sending data to the server, make sure it fits the expected format.
  3. Authentication and Authorization: When working with protected resources, ensure you're handling authentication and authorization correctly, like adding access tokens in request headers.
  4. Pagination and Filtering: When fetching large amounts of data, use query parameters for pagination and filtering.
  5. Caching: To improve performance, cache frequently requested data.
1
Task
Frontend SELF EN, level 44, lesson 1
Locked
Creating a Fetch Record
Creating a Fetch Record
1
Task
Frontend SELF EN, level 44, lesson 1
Locked
Fetch Record Update
Fetch Record Update
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION