2

Anytime I make a delete request to my node js server, it can only delete one item from my json file between server starts. If I try to make a second delete request, it works, but it also rewrites back the last item I deleted.

Here is the node js delete implementation using express:

const todos = require("./todos.json"); //Load the node js File
const fs = require("fs");

app.delete("/api/:id", (req, res) => {
  const id = req.params.id;
  let newTodos = todos.filter((todo) => {
    return todo.id !== id;
  });
  fs.writeFileSync(__dirname + "/todos.json", JSON.stringify(newTodos));
  todos = newTodos;
  res.send("Todo deleted");
});

This is how the items in the json file look they are contained in a regualar array:

  {
    "id": "bd58d991-bdda-4d8d-aca3-ae7ee01e1296",
    "activity": "Buy Groceries",
    "completed": false
  }
3
  • 1
    where is the newTodos variable filled? Commented Sep 25, 2020 at 14:12
  • 1
    because you never update todos with the new content. it's always starting with the original file contents when you call .delete. Commented Sep 25, 2020 at 14:12
  • @Joe I made some changes and it's still not working. Commented Sep 25, 2020 at 14:23

1 Answer 1

3

You should read todos.json at the beginning of delete handler.

app.delete("/api/:id", (req, res) => {
  const todos = fs.readFileSync("./todos.json", { encoding: 'utf-8' })
  ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.