DEV Community

Cover image for React CRUD Operations Made Easy with Array Methods
Amrita-padhy
Amrita-padhy

Posted on

React CRUD Operations Made Easy with Array Methods

What is CRUD ?

CRUD operation in React stands for Create, Read, Update, and Delete. CRUD is an important concept for organizing and managing data across the web application. We will perform CRUD operation in the React application with local storage in the form of JavaScript Objects instead of using JSON servers or Axios in React.

  • Create: Creating a post or adding the table row, adding data to the webpage, or creating content.
  • Read: Reading or retrieving data from a web page
  • Update: Updating or editing existing content on the webpage
  • Delete: Deleting and removing the entry or content/post from the webpage

Here's a guide on which array methods you can use for each CRUD operation:

1. Create (C):
To add a new element to the array, you can use the concat() method or the spread operator (...).

// Using concat
const newArray = oldArray.concat(newElement);

// Using spread operator
const newArray = [...oldArray, newElement];
Enter fullscreen mode Exit fullscreen mode

2-Read (R):
Reading or retrieving data from an array can be done using methods like map(), filter(), or accessing elements by index.

// Using map
const mappedArray = oldArray.map(item => /* transform item if needed */);

// Using filter
const filteredArray = oldArray.filter(item => /* condition */);

// Accessing by index
const elementAtIndex = oldArray[index];
Enter fullscreen mode Exit fullscreen mode

3-Update (U):
Updating data in an array can be done using methods like map() or splice().

// Using map to update a specific item
const updatedArray = oldArray.map(item => item.id === itemId ? updatedItem : item);

// Using splice to replace an item at a specific index
const updatedArray = [...oldArray];
updatedArray.splice(index, 1, updatedItem);
Enter fullscreen mode Exit fullscreen mode

4-Delete (D):
Deleting an element from an array can be achieved with methods like filter() or splice().

// Using filter to remove a specific item
const newArray = oldArray.filter(item => item.id !== itemId);

// Using splice to remove an item at a specific index
const newArray = [...oldArray];
newArray.splice(index, 1);
Enter fullscreen mode Exit fullscreen mode

CRUD operations are fundamental for building applications that interact with databases or any form of data storage.
uses of appropriate method based on your specific use case.

Top comments (0)