YVH
YVH

Reputation: 207

How to remove any firebase data using JavaScript?

I am building a web application using JavaScript and firebase.

everytime I click on the "remove" paragraph tag, I can only remove the most recent added item, but cannot remove the rest.

Example: if I have 9 items, and I just added a 10th item, I can only remove the 10th item, but not the other 9 items. I basically can only remove items in a backwards order, as opposed to being able to remove items in any order of my choice.

Here is my code:

function displayFav(){
  const dbRef = firebase.database().ref();
  dbRef.on("value", (firebaseData) => {
   
   // empty out element before adding new updated firebase data so there are no repeated data
 document.getElementById("displayUsername").innerHTML = "";
 
    let accounts = [];
    const accountData = firebaseData.val();
    
    for (let itemKey in accountData) {
      accountData[itemKey].key = itemKey;
      accounts.push(accountData[itemKey])
      
      const key = accountData[itemKey]["key"];
      const password = accountData[itemKey]["password"];
      let user = accountData[itemKey]["username"];

  // code where I try to render results from page
   document.getElementById('displayUsername').innerHTML += `
      <li> Username: ${user} Password: ${password}</li>
      <p id=${key}>Remove</p>
      `;
      
    // code where I try to remove the item 
     document.getElementById(key).addEventListener("click", function(){
        removeItem(key)
      })
 
      }
    });
  }

This is my function to remove the firebase data:

function removeItem(itemToRemove){
   const dbRef = firebase.database().ref(`${itemToRemove}`);
  dbRef.remove();
};

What can I change or add to my code that will allow me to remove items in any order I want, instead of letting me delete only the most recent items?

Upvotes: 0

Views: 53

Answers (1)

K.Wu
K.Wu

Reputation: 3633

Not trying to be rude, this is just a tip: Please indent/format your code well so that people can understand it without having to format it themselves. Usually when people see large code that's not well formatted, it throws them off (sometimes including me), and therefore they wouldn't want to continue to read or help you with the question.

Suppose you have a table called posts, and the structure looks like this:

enter image description here

that is:

{
    <postId>: {
        date: 1518925839059,
        message: 'some message'
    },
    <postId>: {
        date: 151892583967,
        message: 'some message'
    },
    ...
    ...
}

Suppose you want to delete the extra property of the first post, as circled in the picture, you must know the full path of the data:

firebase.database().ref('posts/-L5b1EZ1L_FycluzTIn8/extra').remove();

If you want to delete everything in post 1:

firebase.database().ref('posts/-L5b1EZ1L_FycluzTIn8').remove();

Or, if you want to delete every single post:

firebase.database().ref('posts').remove();

Upvotes: 0

Related Questions