I am working on a fullstack project. For frontend I am using React. For backend I am using Node, Express, Sequelize and Postgres. On my page I have the Material-table setup and it is fetching data from my backend. Meanwhile I want the editable features to work for adding, updating and deleting from the table.
API ROUTE
router.delete('http://localhost:8004/api/v1/locations/delete/:id', locationController.deleteLocation);
MATERIAL-TABLE EDITABLE SETTING FOR DELETE
onRowDelete: oldData =>
new Promise(resolve => {
setTimeout(() => {
resolve();
const data = [...results.data];
data.splice(data.indexOf(oldData), 1);
axios
.delete("http://localhost:8004/api/v1/locations/delete/:id", {
params: {
id: results.data[0].id
}
})
.then(res => console.log(res.data));
setResults({ ...results, data });
}, 600);
}),
EXPRESS CONTROLLER FOR DELETE ROUTE
exports.deleteLocation = async (req, res) => {
try {
await Location.destroy({ where: { id: req.params.id}});
res.status(200);
res.json(
{
message: 'One Location deleted'
}
);
}
catch(err) {
console.log(err);
res.status(500).json({
message: "There is an error deleting the Location!", err
});
};
};
When I click the delete icon in the material-table, the item will be deleted but on reload it will appear. When I checked my console, I was getting the query DELETE FROM "location" WHERE "id" = ':id'
Somehow I think the problem is in my route and the url I passed to material-table. When I removed the :id
in the url of axios request in material-table i.e http://localhost:8004/api/v1/locations/delete
I got the error that id is undefined in the console.
The delete
request in axios
will not automatically translate your :id
in your url to the id
in your params.
You will need to call that specific url yourself:
axios
.delete(`http://localhost:8004/api/v1/locations/delete/${results.data[0].id}`)