K
K
Kentavr162021-06-07 19:54:15
Mongoose
Kentavr16, 2021-06-07 19:54:15

How to write a delete request?

in the process of learning I am making a site - a shell. here is the code:
express routes:

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
const Task = require('../models/Task');

// return all tasks
router.get('/getTask', function(req, res) {
    Task.find({}, function(error,data){
        if(error){
            console.log(error)
        }
        res.send(data)
    })
})

//create new task
router.post('/newTask', function(req,res){
    if(!req.body) return res.sendStatus(400);
    var a = new Date();
    var mydate = a.toLocaleString();
    Task.create({
        description:req.body.description,
        task:req.body.task,
        addDate: mydate
    },
    function(err){
        if(err)
        res.send(err);
    })
    res.send("Task has been created")
})

module.exports = router


react element for displaying information received from the database:
import React from 'react'
import axios from "axios"

class LoadTask extends React.Component{
    constructor(props) {
        super(props);
        this.state = {items:[],
            key : 0,

        };
        
    }

    



    async componentDidMount() {
        try {axios.get('http://localhost:5000/api/getTask')
        .then(response => this.setState({items: Object.values(response.data)}));} 
        catch ( error ) {
            console.log(error)
        }; 
    }

    
    render() {

        
    

    return(
        <div className="loadTaskWrap">
            <p>Здесь ты можешь просмотреть существующие таски:</p>
            <div className="desP">
                <div>{this.state.items.map((item) =>
                (<div key={item.description} className='styleTask' >
                    <p className="stDesk" >{item.description}:</p>
                    <div>{item.task}
                    </div>
                    <div>{item.addDate}</div>
                <button>Удалить задачу</button>
                <button>Отметить как выполненную</button>
                </div>))}</div>
            </div>
        </div>
    )
}


}

export default LoadTask


I was overtaken by a stupor - how in my case to competently implement the removal of my task by clicking on the "delete task" button? Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Shvedov, 2021-06-07
@mmmaaak

1) a request for a back with the ID of the element to be deleted
2) on the back you delete the element from the database by ID
3) send a response with the result of the operation, if the deletion was successful - delete the element from the list on the front, if not - show an error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question