My express react App keeps on giving me the error that It cannot find my api
I am building a React + express website which allows users to make webProjects. It displays these projects in a table. The user is able to add, and edit the web projects. I am adding a function which allows the user to delete an item by pressing the delete button next to the items. My function works in Postman but I cant get it to work when I press the button in the frontend
TableData.js
import React, {useState, useEffect} from 'react'
export const TableData = ({ projectData, fillInput, setContent, selectedProject }) => {
console.log(projectData)
const [deleteID, setDeleteID] = useState("");
useEffect(() => {
if (selectedProject) {
setDeleteID(selectedProject.ID);
console.log(selectedProject)
}
}, [selectedProject])
//This is a function which deals with deleting a webProject
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);
setContent({ projectData: updatedProjects }); // This Code for update the state
})
}
return (
My Projects
ID
Title
Description
URL
{projectData.map((projectData, index) => (
{projectData.ID}
{projectData.TITLE}
{projectData.DESCRIPTION}
{projectData.URL}
fillInput(projectData)}>edit
deleteItem(projectData.ID)}>Delete
))}
)
}
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);
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 (
{/* The props are sent to provide the FormData component with information
about the currently selected project which will be used when editing a project. */}
)
}
export default App
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);
})
0 comments:
Post a Comment
Thanks