So I want to add delete button, but when I click it I see error:
‘TypeError: props.onDeleteTask is not a function’ – in component – SingleTask.js
//../components/SingleTask.js
(...)
function deleteTask(props){
const dataId = props.id;
props.onDeleteTask(dataId)
}
(...)
<div className={classes.delete}>
<img onClick={deleteTask} src="/delete.png" alt="delete" />
</div>
///
//../components/AllTask.js
const AllTask = (props) => {
return (
<ul className={classes["all-tasks"]}>
{props.tasks.map((task) => (
<SingleTask
key={task.id}
id={task.id}
title={task.title}
priority={task.priority}
start_date={task.start_date}
complete={task.complete}
description={task.description}
onDeleteTask={props.onDeleteTask}
/>
))}
</ul>
//
//../pages/index.js
function Home(props) {
async function deleteTaskHandler(enteredTaskData) {
const response = await fetch("/api/helper", {
method: "DELETE",
body: JSON.stringify(enteredTaskData),
headers: {
"Content-Type": "application/json",
},
});
const data = await response.json();
console.log(data);
}
return (
<Fragment>
<AllTask tasks={props.tasks} onDeleteTask={deleteTaskHandler} />
</Fragment>
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
3
Answers
Your "function" is not really a function for
onDeleteTask
You need to invoke the
function
Try to fix this in the
../components/SingleTask.js
fileI recommend you to use
useContext
it can help you better with theselife cycle components
futures and also avoiddrilling props
.I believe your error is because the OnClick event send 1 parameters to the function wich is the event. In your case the function deleteTask is receiving the event as params wich you name "props". You could fix this by using this syntax :
Or just removing the params props from your function declaration since you don’t look like your using the event anyway.
You are binding deleteTask function to the
onClick
that passes click event as params. And the function is getting it as named props.So, that props is that property you are passing into the SingleTask componenet.
Please try to change the code part as below:
//../components/SingleTask.js
Does it make sense?