'API issue | URL with parameter
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);
});
Solution 1:[1]
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' });
}
});
Solution 2:[2]
get index is -1; you should check it before splice; or use filter
Solution 3:[3]
Problem:
- find also return
undefinedIf it does not find the item. - when you search for the undefined index it'll return
-1 - if you pass
-1tospliceIt'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);
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | madzong |
| Solution 2 | ????? |
| Solution 3 |
