Search code examples
reactjsspringcrud

Spring boot, react how to delete entity of specific id?


I'm trying to make a simple CRUD app. I'd like to delete a student of a specific id but I'm getting 400 error. My controller class in Spring boot looks like this:

@DeleteMapping("/student/delete/{id}")
public String deleteById(@PathVariable int id){
        studentService.deleteStudentById(id);
        return "Student deleted";
}

In React my delete function looks like this:

    const handleDelete = (id) => {
    fetch("http://localhost:8080/student/delete/{id}", {
        method: "DELETE",
        headers: {"Accept":"application/json", "Content-Type":"application/json"}
    }).then(() => {
        let updatedStudents = [...students].filter(i => i.id !== id);
        setStudents(updatedStudents);
    });
}

In my app I'm rendering students from MySQL database, each one with uniqe id. Each student has a delete button with onClick function => handleDelete. Where can be the problem?


Solution

  • Pass the id, you missed that

    const handleDelete = (id) => {
    fetch("http://localhost:8080/student/delete/"+id, {
        method: "DELETE",
        headers: {"Accept":"application/json", "Content-Type":"application/json"}
    }).then(() => {
        let updatedStudents = [...students].filter(i => i.id !== id);
        setStudents(updatedStudents);
    });
    }