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>
);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CodePudding user response:
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 :
onClick={() => deleteTask()}
Or just removing the params props from your function declaration since you don't look like your using the event anyway.
function deleteTask(){ ...
CodePudding user response:
Your "function" is not really a function for onDeleteTask
You need to invoke the function
Try to fix this in the ../components/SingleTask.js
file
<div className={classes.delete}>
<img onClick={() => deleteTask()} src="/delete.png" alt="delete" />
</div>
I recommend you to use useContext
it can help you better with these life cycle components
futures and also avoid drilling props
.
CodePudding user response:
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
...
const {onDeleteTask, id} = props;
...
<div className={classes.delete}>
<img onClick={() => onDeleteTask(id)} src="/delete.png" alt="delete" />
</div>
Does it make sense?