Home > Software design >  in JS, how to delete ALL items in a JSON file?
in JS, how to delete ALL items in a JSON file?

Time:08-11

Im running a json server locally (npx json-server extras/db.json) (localhost 3000) and the db.json file is shown at the end of this request. I am able to delete a specific item by id as shown immediately below.

How do I delete ALL items?

(I tried url "http://localhost:3000/expenses" (which displays all items in browser) but get error "DELETE http://localhost:3000/expenses 404 (Not Found)" and it does not delete.)

I can delete a specific item using:

   export async function deleteExp(id) {
      const settings = {
        method: 'DELETE',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json'
        }
      }
      try {
        const url = `http://localhost:3000/expenses/${id}`
        const response = await fetch(url, settings)
        const data = await response.json()
        return data
      } catch (e) {
        console.log('Error', e)
        return e
      }
    }

JSON file (db.json)

{
  "expenses": [
    {
      "id": 22,
      "name": "car payment",
      "amount": 300
    },
    {
      "id": 23,
      "name": "student loan",
      "amount": 400
    },
    {
      "id": 24,
      "name": "credit card",
      "amount": 800
    }
  ]
}

CodePudding user response:

You can delete all items, by looping over the array of expenses; and each loop call the function deleteExp(id) with the id of expense:

const expenses = {
  expenses: [
    {
      id: 22,
      name: "car payment",
      amount: 300,
    },
    {
      id: 23,
      name: "student loan",
      amount: 400,
    },
    {
      id: 24,
      name: "credit card",
      amount: 800,
    },
  ],
};
for (const expense of expenses) {
  await deleteExp(expense.id);
}

BUT Note this is not an efficient way of doing delete all items, To do so you need to make a route /expenses with delete method in backend, so there do your process of deleting items!

  • Related