By clicking the delete button I’m expecting to filter a parent app.js component array and delete a particular item. But I’m getting a Typescript error Cannot assign to read only property ‘message’ of object ‘SyntaxError: /src/components/TaskComponent.tsx: Identifier ‘deleteTask’ has already been declared., for I’m typing a handle delete as a prop. Also do I need to filter the main Tasks array twice, in the child and in the parent component ?
// Child component
import React, { useState, FC } from "react";
type Tasks = {
title: string;
author: string;
description: string;
status: number | any;
priority: number | any;
};
type Props = {
Tasks: Tasks[];
changeTask: (tasks: Tasks) => {};
deleteTask: (id: Tasks) => {};
};
const TaskComponent: FC<Props> = ({ Tasks, changeTask, deleteTask }) => {
const deleteTask = (id) => {
Tasks.filter(task => task.id === id)
};
return (
...
<input type="button" value="delete" onClick={deleteTask} />
)
}
// App.js component
const Tasks = [
{
id: "001",
status: 0,
priority: 2,
title: "Develop website homepage",
description:
"Create a visually appealing and responsive homepage for the website",
schedule: {
creation_time: "2021-07-23T10:00:00"
},
author_name: "John Smith"
},...
}
function App() {
const [tasks, setTasks] = useState(Tasks);
const deleteTask = (id) => {
setTasks((tasks) => tasks.filter((task) => task.id === id));
};
return (
<TaskComponent
Tasks={tasks}
changeTask={changeTask}
deleteTaskP={deleteTask}
/>
2
Answers
In the TaskComponent you pass deleteTask as a prop and then you declare variable with the same name inside of the TaskComponent. You cannot do that, just use different name if you need to preserve both.
You’re destructuring your props, so basically
({deleteTask})
meansconst deleteTask = ...
inside of the TaskComponentA starting issue would be that inside
App.tsx
you are passing a prop nameddeleteTaskP
– a typo or was it your intention instead ofdeleteTask
– which is what you seem to be expecting as prop in your Child componentTaskComponent
and instead would have a value ofundefined
(destructuring non-existant property), so modifyApp.tsx
:And then inside
TaskComponent
you are already expecting a prop nameddeleteTask
and both trying to create adeleteTask
of the similar functionality, so don’t clash the names, but if you do need a new function then use a different name, remove that fromTaskComponent.tsx
:Additionally in your CodeSandbox I noticed your
type Tasks
has a wrong property nameauthor
instead ofauthor_name
inside the sameTaskComponent.tsx
: