How to Delete Firebase Values [Building a Mobile App Lesson]

Hi,

From the JS Building a Mobile App lessons, I would like to delete/clear the value of the Firebase Database from the ShoppingList every 24 hours. Unfortunately, I wasn’t able to find a Firebase method that takes a snapshot like onValue.

So, I created my function as below. The full code is in the repo.

//save FB DB locations in array
let DBLocations = [];

//this function is from the course
function appendItemToShoppingListEl(item) {
  let itemID = item[0];
  let itemValue = item[1];
  let exactLocationOfItemInDB = ref(database, `shoppingList/${itemID}`);
  DBLocations.push(exactLocationOfItemInDB);

  let newEl = document.createElement("li");

  newEl.textContent = itemValue;

  newEl.addEventListener("dblclick", function () {
    remove(exactLocationOfItemInDB);
  });

  shoppingListEl.append(newEl);
}

//clear DB every 24 hours
if (DBLocations.length > 0) {
  setInterval(clearDB, 86400000);
}

function clearDB() {
  for (let item of DBLocations) {
    remove(item);
  }

  DBLocations = [];
}

I’m wondering if there is better way to clear the database in Firebase? The above code appears to work.

App: https://vincentwebdev.github.io/shopping-list/

Repo: https://github.com/VincentWebDev/shopping-list

Hey Vincent!

I think the way you have done it is absolutely fine in the context of a demo app and there’s no better way provided by Firebase to do this. In the real world you would want to do this from server-side not on the front end so if you feel ready you could investigate Firebase Cloud functions!

Good luck!!