How to push new data to Array with Firebase

I'm having trouble with updating an array. Essentially I have a list of items that I am rendering a checkbox on. When I select the checkbox, a database reference pulls the strings for the items connected to the checkbox. I can get the data from each individual item, but my array never updates, it always stays empty. I basically need to update the array with each additional list item I press the checkbox on.

  const onChangeValue = (Item) => {

    /*firebase.database()
      .ref('users/' + '/C Room' + '/' + Item.Id)
      .remove()
      .then(() => { })
      .catch((err) => {
        console.log(err);
      });*/
      const leadsRef = firebase.database().ref('users/' + '/C Room' + '/' + Item.Id);
      leadsRef.on('value', function(snapshot) {
          snapshot.forEach(function(childSnapshot) {
            const childData = childSnapshot.val();
          //console.log(childData)
           const checkboxData = childData
          //setcheckboxArray(childData)
        console.log(checkboxData)
          setTheArray(theArray => [...theArray, checkboxData]);
        
         
          });
          console.log(theArray)
      });

  }
pearl
-NBhaGshkMgGLbslqXZQ
rRs584c
C Room
drums
Array [
  "",
]

The values only ever return one at a time and they wont add to the array.

Upvotes: 0

Views: 491

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

There's never a need to call them multiple times in a tight loop like you do here.

To fix that:

const leadsRef = firebase.database().ref('users/' + '/C Room' + '/' + Item.Id);
leadsRef.on('value', function(snapshot) {
    let arr = [];
    snapshot.forEach(function(childSnapshot) {
      arr.push(childSnapshot.val());
    });
    setTheArray(arr);
});

Upvotes: 2

Related Questions