user3802348
user3802348

Reputation: 2592

Update value of variable from Firebase query?

I currently am trying to pull the value of an item from a firebase using once, and use this value to populate the var itemsList. However, although itemsList is correctly populated within the once call, it is logging as undefined outside the call. I think this may have something to do with the asynchronous nature of Firebase, but I'm not sure how to remedy this problem. Any suggestions?

submitAnswer: function() {
    var userRef = usersRef.child(key);

    //get items_list for user
    var itemsList;
    userRef.once('value', (snap) => {
        itemsList = snap.val().items_list;
        console.log('items list populated here' + itemsList);
    });

    console.log("items list not populated here" + itemsList);
},

Upvotes: 0

Views: 887

Answers (1)

Brad Colthurst
Brad Colthurst

Reputation: 2605

You're correct about the Firebase call, it's asynchronous and the code isn't going to wait for it to complete before logging the unpopulated itemsList.

If you're only looking to do something simple with the data, just be sure to check that it exists before performing any action with it (and handle it like you would any async data).

if(itemsList){
  console.log('My items have arrived! ' + itemsList);
}

If that data is going to be propagated further down your app it is usually suggested to make a call to setState() with your response data from Firebase to trigger a re-render of your components with the new data you just fetched.

So something along the lines of:

userRef.once("value", (snap) => {
  itemsList = snap.val().items_list;

  this.setState({
    items: itemsList;
  });

}.bind(this));

Upvotes: 2

Related Questions