7 May 2024
useState
hook, combined with the power of JavaScript array methods, allows for effective and efficient manipulation of array data in your components. In this guide, we'll explore how to update and delete items in an array stored in state.map
method. This method creates a new array with the results of calling a provided function on every element in the calling array. Here’s how you can update an item in an array using useState
.import React, { useState } from 'react';
const TaskUpdater = () => {
const [tasks, setTasks] = useState([
{ id: 1, name: 'Task 1', completed: false },
{ id: 2, name: 'Task 2', completed: false },
{ id: 3, name: 'Task 3', completed: false }
]);
const updateTask = (id) => {
setTasks(tasks.map(task =>
task.id === id ? { ...task, completed: !task.completed } : task
));
};
return (
<div>
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.name} - {task.completed ? 'Completed' : 'Pending'}
<button onClick={() => updateTask(task.id)}>Toggle Status</button>
</li>
))}
</ul>
</div>
);
};
export default TaskUpdater;
In this example:
tasks
state is initialized with an array of task objects.updateTask
function toggles the completed
status of a task based on its id
.filter
method. This method creates a new array with all elements that pass the test implemented by the provided function.id
.import React, { useState } from 'react';
const TaskDeleter = () => {
const [tasks, setTasks] = useState([
{ id: 1, name: 'Task 1', completed: false },
{ id: 2, name: 'Task 2', completed: false },
{ id: 3, name: 'Task 3', completed: false }
]);
const deleteTask = (id) => {
setTasks(tasks.filter(task => task.id !== id));
};
return (
<div>
<ul>
{tasks.map(task => (
<li key={task.id}>
{task.name} - {task.completed ? 'Completed' : 'Pending'}
<button onClick={() => deleteTask(task.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default TaskDeleter;
In this example:
deleteTask
function removes a task by its id
using the filter
method.useState
hook and JavaScript array methods like map
and filter
. These techniques allow you to efficiently manage dynamic arrays and ensure your state updates remain immutable and predictable. By mastering these methods, you can handle more complex state management scenarios in your React applications with ease.