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:
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:
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:
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:
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:
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:
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:
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:
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:
- Error Handling: Always handle potential errors when performing HTTP requests. Use
try...catchblocks orcatchmethods for error handling. - Data Validation: Before sending data to the server, make sure it fits the expected format.
- Authentication and Authorization: When working with protected resources, ensure you're handling authentication and authorization correctly, like adding access tokens in request headers.
- Pagination and Filtering: When fetching large amounts of data, use query parameters for pagination and filtering.
- Caching: To improve performance, cache frequently requested data.
GO TO FULL VERSION