I am learning REST API. I am using the react app for front end and backend for Node js and express server. For API I am using REST API. I am using MongoDB for the database. I successfully display all the data to the browser. I can able to search the data. Now I want to delete the data. I don't know how to delete data from REST API endpoint. I will be really glad if someone help me out. I tested my backend by using Postman. Everything works fine as expected.
This is my backend delete end point
app.delete("/students/:id", async (req, res, next) => { const id = req.params.id; try { student .remove({ _id: id }) .exec() .then(data => { res.json(data); }); } catch (error) { console.log(error); }});
I export my API END points to React js
export async function deleteStudent(id) { const response = await fetch(`/students/${id}`, { method: "DELETE" }); return response.json();}
This is the main component where I want to delete the data
import React, { useState, useEffect } from "react";import { logEntry } from "../Api/Api";import { deleteStudent } from "../Api/Api";function Datatable() { const [total, settotal] = useState([]); const [searchItem, setsearchItem] = useState({ item: "" }); const [data, setdata] = useState([]); const handleChange = e => { setsearchItem({ item: e.target.value }); }; const getEntries = async () => { const logEntries = await logEntry(); console.log(logEntries); settotal(logEntries.count); setdata(logEntries.students); }; const nameFilter = data.filter(list => { return list.name.toLowerCase().includes(searchItem.item.toLowerCase()); }); const deleteData = async id => { await deleteStudent(id); }; useEffect(() => { getEntries(); }, []); return (<div><div style={{ paddingLeft: "800px" }}><input placeholder="Search student" onChange={handleChange} style={{ width: "200px", height: "30px" }} /></div><p>Total student: {total} </p><table><thead><tr><th>Name</th><th>City</th><th>Address</th><th>Phone</th><th>Email</th></tr></thead><tbody> {nameFilter === "" ? (<p>Student not found</p> ) : ( nameFilter.map(list => { return (<tr><td>{list.name}</td><td>{list.city}</td><td>{list.address}</td><td>{list.phone}</td><td>{list.email}</td><td><a className="waves-effect red btn-small" onClick={() => deleteData(list.id)}> Delete</a></td></tr> ); }) )}</tbody></table></div> );}export default Datatable;
I don't know, Am I doing?