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}
/>
>Solution :
A starting issue would be that inside App.tsx you are passing a prop named deleteTaskP – a typo or was it your intention instead of deleteTask – which is what you seem to be expecting as prop in your Child component TaskComponent and instead would have a value of undefined (destructuring non-existant property), so modify App.tsx:
function App() {
// ...
return (
<TaskComponent
Tasks={tasks}
changeTask={changeTask}
// deleteTaskP={deleteTask}
deleteTask={deleteTask}
/>
}
And then inside TaskComponent you are already expecting a prop named deleteTask and both trying to create a deleteTask 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 from TaskComponent.tsx:
const TaskComponent: FC<Props> = ({ Tasks, changeTask, deleteTask }) => {
// Remove (or rename) this function and instead use 'deleteTask' prop
// const deleteTask = (id) => {
// Tasks.filter(task => task.id === id)
// };
return (...);
}
Additionally in your CodeSandbox I noticed your type Tasks has a wrong property name author instead of author_name inside the same TaskComponent.tsx:
type Tasks = {
id: string;
title: string;
// author: string; // make sure to rename into:
author_name: string;
description: string;
status: number | any;
priority: number | any;
};