I’m expecting to delete a task in a App.js array by filtering. But the array keeps the same after clicking the delete button in the Task child component. Even though I’m passing an id as a function attribute.
// App.js component
function App() {
const [tasks, setTasks] = useState(Tasks);
const deleteTask = (id) => {
Tasks.filter((task) => task.id === id);
};
return (
<TaskComponent
Tasks={tasks}
changeTask={changeTask}
deleteTask={deleteTask}
/>
)
// TaskComponent
type Tasks = {
id: string;
title: string;
author_name: string;
description: string;
status: number | any;
priority: number | any;
};
type Props = {
Tasks: Tasks[];
changeTask: (tasks: Tasks) => {};
deleteTask: (tasks: Tasks) => {};
};
const TaskComponent: FC<Props> = ({ Tasks, changeTask, deleteTask }) => {
const history = useHistory();
const { id } = useParams<IdParams>();
const task = Tasks.find((task) => String(task.id) === id);
const [status, setStatus] = useState(task?.status);
const [priority, setPriority] = useState(task?.priority);
const handleDeleteTask = () => {
deleteTask({
...task,
id
});
history.push("/taskslist");
};
return (
<form>
<input type="button" value="delete" onClick={handleDeleteTask} />
</form>
)
3
Answers
It looks like you need to use the setter method
setTasks
in order to set the tasks prop on your app like this:So… what is deleteTask? Do you need to update a state above TaskComponent with a new
Tasks
value for TaskComponent i.e. a selection of tasks which does not include this task in question.So your issue lies in this:
Does filter delete a task? No – ok so maybe you need to map / reduce / filter to create a new reference object without the task you want to delete and update the state in the parent i.e. use
setTasks
Problem :- you filter directly Task List that the problem page is not re-render..
Solution :-