I am struggling to get my delete request to work in my express + react app

Issue

I am busy creating a web Projects application which allows the user to display, add, edit and delete a number of web projects that they have set up including three premade projects. I have gotten everything besides my delete function to work. I know that my delete function does work in the backend because I have tested it in postman. I dont know how to get it to work when I press my delete button in my table.

server.js
app.delete("/api/delete", (req, res) => {
    const projectId = parseInt(req.body.id);
    const projectIndex = webProjects.findIndex(project => project.ID === projectId);

    if (projectIndex === -1) {
        return res.status(404).send("Project not found");
    }

    webProjects.splice(projectIndex,1);
    //res.send(`The item was successfully deleted`)
    res.send(webProjects);
})

TableData.js
import React, {useState} from 'react'

export const TableData = ({ projectData, fillInput }) => {
  console.log(projectData)


  const deleteItem = () => {
    fetch("/api/delete", {
      method: "DELETE",
      headers: {
      "Content-Type": "application/json"
  }})
  .then((response) => response.json())
  .then((response) => {
    console.log(response)
  })

}

  return (
    <div>
    <div className="tableheading">
    <strong>My Projects</strong>
  </div>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>Title</th>
        <th>Description</th>
        <th>URL</th>
      </tr>
    </thead>
    <tbody>
        {projectData.map((projectData, index) => (
            <tr key={projectData.ID}>
                <td>{projectData.ID}</td>
                <td>{projectData.TITLE}</td>
                <td>{projectData.DESCRIPTION}</td>
                <td>{projectData.URL}</td>
                <td><button type="button" onClick={() => fillInput(projectData)}>edit</button></td>
                <td><button type="button" onClick={() => deleteItem()}>Delete</button></td>
            </tr>
        ))}
    </tbody>
  </table>
</div>

)
}

App.js
import React, { useEffect, useState } from 'react'
import { TableData } from './components/TableData'
import FormData from './components/FormData'



function App() {

  const [content, setContent] = useState({ webProjects: []});
  const [selectedProject, setSelectedProject] = useState(null);

  const [TITLE, setTITLE] = useState("");
  const [DESCRIPTION, setDESCRIPTION] = useState("");
  const [URL, setURL] = useState("");

  useEffect(() => {
fetch("/api", {
  method: "GET",
  headers: {
    "Content-type": "application/json",
  }
}).then((response) => response.json()
).then((response) => {setContent(response)}
)

}, [])

  const  fillInput = (project) => {
    setSelectedProject(project)
  }

  const  fillInputId = (project) => {
    setSelectedProject(project.ID)
  }

  return (
    <div>
      <TableData 
        projectData={content.webProjects}
        fillInput={fillInput}
  />
  {/* The props are sent to provide the FormData component with information 
  about the currently selected project which will be used when editing a project. */}
  <FormData 
    selectedProject={selectedProject}
    setSelectedProject={setSelectedProject}
    fillInputId={fillInputId}
  />
</div>

)
}

export default App

Solution

It seems like you are not providing the Specific ID that should be deleted.

const deleteItem = (projectId) => {
  fetch("/api/delete", {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({ id: projectId }) // ID to delete
  })
  .then((response) => response.json())
  .then((updatedProjects) => {  
    console.log(updatedProjects);
  })
}

And then pass the ID when the button clicked, like this

<button type="button" onClick={() => deleteItem(projectData.ID)}>
    Delete
</button>

Note: When you delete the item, make sure you also update the state so-that you get the latest updated item!

Example:-

.then((updatedProjects) => {
    console.log(updatedProjects);
    setContent({ webProjects: updatedProjects }); // This Code for update the state
  })

Answered By – Kayes

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published