CRUD, which stands for Create, Read, Update, and Delete, is a fundamental aspect of any web application. In this blog post, we will explore how to implement the CRUD operations using React's useState and useEffect hooks. These hooks allow us to manage state and side effects in functional components, making our code more readable and maintainable.
We will start by using useState to create a state variable for our data, which will be an array of items. We will also create a setter function to update the state, which will be used to add, edit, and delete items from the array.
import { useState, useEffect } from 'react';
function MyComponent() {
const [items, setItems] = useState([]);
const addItem = (item) => {
setItems([...items, item]);
}
const editItem = (index, item) => {
const newItems = [...items];
newItems[index] = item;
setItems(newItems);
}
const deleteItem = (index) => {
const newItems = [...items];
newItems.splice(index, 1);
setItems(newItems);
}
return (
<div>
<button onClick={() => addItem({ name: "New Item" })}>Add Item</button>
<table>
<tbody>
{items.map((item, index) => (
<tr key={item.name}>
<td>{item.name}</td>
<td>
<button onClick={() => editItem(index, { name: "Edited Item" })}>Edit</button>
<button onClick={() => deleteItem(index)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
In the above example, we have created 3 functions addItem, editItem, and deleteItem which will update the state of the items. In the render function, we have mapped through the items and displayed them in a table. We have also added buttons to edit and delete items.
Next, we will use useEffect to fetch data from an API and update our state. useEffect takes two arguments: a function that will run when the component is rendered, and an array of dependencies, which determine when the effect should be run. In this case, we want to fetch data when the component is first rendered, so we will pass an empty array as the second argument.
import { useState, useEffect } from 'react';
function MyComponent() {
const [items, setItems] = useState([]);
useEffect(() => {
fetch('https://my-api.com/items')
.then(response => response.json())
.then(data => setItems(data))
}, []);
// ...rest of the component remains the same
}
In the example above, when the component is first rendered, the useEffect function will run and fetch data from the API. It will then update the state with the data
Top comments (0)