How to delete task from todo list as well as mysql

61 Views Asked by At

I am working on todo list using react node.js and mysql but I cant delete the task from mysql database. How to delete the tasks from mysql database using todo list? Please help me.

My React code:

import { type } from '@testing-library/user-event/dist/type';
import React, {useState} from 'react';
import './clint.css'
export default function Addtask(){
    const [task,setTask]=useState([]);
    const [text,setText]=useState('');
    const obj=[{task:text.trim(),id:task.length}];
    const deleteTodo=async(i)=>{
        try{
        
            var newTask=task;
            newTask.splice(i,1);
            setTask([...newTask]);
            console.log(i);
            const resp= await fetch('http://localhost:5000/delete',{
                method:'POST',
                body:JSON.stringify(task[i-1]),
                headers:{'content-type':'application/json'}
            });
            console.log(resp.body.i);
            if(resp.status===200){
                console.log('task deleted successfully');
            }
            else{
                console.log('task does not deleted');
            }
        }
        catch(error){
            console.log("error");
        }
    }
    const handleSubmit = async(event)=>{
        event.preventDefault();
        try{
            setTask([...task,obj[obj.length-1].task]);
            const resp= await fetch('http://localhost:5000/addtask',{
                method:'POST',
                body:JSON.stringify(task),
                headers:{'content-type':'application/json'}
            });
            console.log(resp.body.text);
            if(resp.status===200){
                console.log('task added successfully');
            }
            else{
                console.log("unable to post");
            }          
        }
        catch(error){
            console.log("error");
        }
    }
    function change(e){
        const ip=e.target.value;
        setText(ip);
    }
    return(
        <div>
            <h1>add user component</h1>

                <span>Add Task</span>
                <input onChange={change} placeholder='add a task'/>
                <button type='submit' onClick={handleSubmit}>submit</button>
            <ul>
                {task.map((tasks,i)=><li key={i}>{tasks}<button className='delete' onClick= 
                {()=>{deleteTodo(i)}}><b>X</b></button></li>)}                
           </ul>
        </div>
    )
}

My NodeJS code:

const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const app = express();
const cors= require("cors");
const mysql2= require('mysql2');

app.use(bodyParser.json());
app.use(cors());
// Create a MySQL connection
const db = mysql2.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'todo_list',
});
var count=0;
// Define API routes for CRUD operations
app.post('/addtask', (req, res) => {
    const ADD_QUERY=`INSERT INTO tasks (id,task) VALUES ('${count++}','${req.body[count-1]}')`;
    db.query(ADD_QUERY,(err,res)=>{
      if(err) throw err;
      else
        console.log(res);
    })
});

app.post('/api/todos', (req, res) => {
  // Create a new to-do item and store it in the database
});

app.put('/api/todos/:id', (req, res) => {
  // Update a to-do item in the database
});

app.post('/delete', (req, res) => {

  const DELETE_QUERY=`DELETE FROM tasks WHERE task =('${req.body[i]}')`;
    db.query(DELETE_QUERY,(err,res)=>{
        console.log(`DELETE FROM tasks WHERE task =('${req.body[i]}')`);
    })
});

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

When I am trying to run the codes the following error is coming

SyntaxError: Unexpected token 2 in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (C:\Users\Administrator\node_modules\body-parser\lib\types\json.js:169:10)
    at parse (C:\Users\Administrator\node_modules\body-parser\lib\types\json.js:86:15)
    at C:\Users\Administrator\node_modules\body-parser\lib\read.js:128:18
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at invokeCallback (C:\Users\Administrator\node_modules\raw-body\index.js:238:16)
    at done (C:\Users\Administrator\node_modules\raw-body\index.js:227:7)
    at IncomingMessage.onEnd (C:\Users\Administrator\node_modules\raw-body\index.js:287:7)
    at IncomingMessage.emit (node:events:513:28)
    at endReadableNT (node:internal/streams/readable:1359:12)
0

There are 0 best solutions below