So I'm working with NodeJS, MongoDB and ReactJS.
I have a Task List where I add -(Task.create) with mongoose- to my project multiple tasks and I have a form with a button to delete those tasks, but I can't do it because I can't access to each task ID to delete it.
Here's my server:
(This is wrong, "task is not defined" but I don't know how to get each task id)
exports.delete_task= (req, res) => {
Task.findByIdAndDelete({tasks: task._id}, (err) =>{
if(err){
console.log(err);
}
})
};
Here's my (reactjs) Tasks Component
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faTrashAlt, faEdit } from '@fortawesome/free-solid-svg-icons'
import './Tasks.css';
class Tasks extends Component {
constructor(props) {
super(props);
this.state = {
projectId: props._id,
tasks: []
};
}
componentDidMount() {
fetch(`/dashboard/project/${this.props.projectId}/tasks`)
.then(response => {
return response.json()
}).then(task => {
this.setState({
tasks: task.tasks
})
}).catch(error => console.error('Error:', error));
}
render() {
const { tasks } = this.state;
return (
<div>
<ul className="task-list">
{tasks.map(task =>
<li key={task._id}>{task.tasktitle}
<div>
<form method='POST' action={`/dashboard/project/${this.props.projectId}/tasks/delete?_method=DELETE`}>
<button className="btn button--tasks" >
<FontAwesomeIcon icon={faTrashAlt} />
</button>
</form>
</div>
</li>
)}
</ul>
</div>
);
}
}
export default Tasks;
Here's an image of my task list, where I can ADD but can't DELETE it because I can't access to each task ID by clicking its own trash button..
Hope you can help me. Thank you so much!!
Do it like below. While doing .map pass task._id
as query param to the path like below
{tasks.map(task =>
<li key={task._id}>{task.tasktitle}
<div>
<form method='POST' action={`/dashboard/project/${this.props.projectId}/tasks/delete?_method=DELETE&taskId=${task._id}`}>
<button className="btn button--tasks" >
<FontAwesomeIcon icon={faTrashAlt} />
</button>
</form>
</div>
</li>
)}
exports.delete_task= (req, res) => {
And here get the task id using req.query.taskId
Task.findByIdAndDelete({tasks: req.query.taskId}, (err) =>{
if(err){
console.log(err);
}
})
};