I have an issue with my Delete function, it is deleting always the last data and not the desired data.
Here's my API - DELETE function:
Function to delete the data
app.delete("/api/theTasks/:id", (req, res) => {
let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
let index = Items.indexOf(taskToRemove);
Items.splice(index, 1);
res.json(taskToRemove);
});
CodePudding user response:
My guess is that the task is not found and index
ends up being -1
, so you end up calling:
Items.splice(-1, 1);
which removes the last element of Items
.
You can fix the issue by checking if the item was found and only deleting it if that is true.
app.delete("/api/theTasks/:id", (req, res) => {
let taskToRemove = Items.find(p => p.id == parseInt(req.params.id));
if (taskToRemove) {
let index = Items.indexOf(taskToRemove);
Items.splice(index, 1);
res.json(taskToRemove);
} else {
res.status(404).json({ error: 'Item not found' });
}
});
CodePudding user response:
get index is -1; you should check it before splice; or use filter
CodePudding user response:
Problem:
- find also return
undefined
If it does not find the item. - when you search for the undefined index it'll return
-1
- if you pass
-1
tosplice
It'll always remove the last element.
Use array filter,
app.delete("/api/theTasks/:id", (req, res) => {
const result = Items.filter((p) => p.id === parseInt(req.params.id));
if (result.length === 0) res.status(404).json({ error: "Item not found" });
res.json(result);
});