0
votes

Problem

I am trying to retrieve data off of my firevase server, and the reference code I am using to do so doesn't retrieve anything.

getItems(){

    var items = [];

    var query = firebase.database().ref('users').child(expoID).orderByKey();

    query.once('value', (snap) => {

       var items = [];

       snap.forEach( (child) => {

            items.push({

       content: child.val().content,

       postKey: child.val().okey,

       color: child.val().color,

       notifKey: child.key

            });

        });

        items.reverse();

        }).then(() => {

        this.setState({firebaseItems: items});

    });

}

expoID is a predefined variable, defined with expo's constants.

Server

firebase server The first items under users is the expoID seen in the code above. I tested, and its the same ID.

1

1 Answers

0
votes

orderByKey only creates a Query. To retrieve the actual data you need to listen for an event. once and on are your friends here. There are following event types: "value", "child_added", "child_changed", "child_removed" and "child_moved."

To get the data use "value". So the code to get your data once for example is:

ref('users').child(expoID).orderByKey().once('value').then(function(snapshot) {
   console.log(snapshot.val());
});

Hope this helps!

EDIT:

// Notice I removed the first declaration of var items
// var items = [];

var query = firebase.database().ref('users').child(expoID).orderByKey();

query.once('value', (snap) => {

  // This array is ONLY valid inside this callback
  var items = [];

  snap.forEach((child) => {
    items.push({
      content: child.val().content,
      postKey: child.val().okey,
      color: child.val().color,
      notifKey: child.key
    });
  });
  items.reverse();
  this.setState({ firebaseItems: items });
});
// No need to set your state in the promise. Just do it directly inside the callback