user3802348
user3802348

Reputation: 2582

How to handle asynchronous calls to Firebase in React-Native app?

I am currently trying to set the initial state of my application to a value pulled from Firebase. However, I can't figure out how to properly handle the asynchronous nature of Javascript--currently when I get the state of the application in my render function, itemsList is undefined. Any suggestions for what I'm doing wrong would be greatly appreciated.

  getInitialState: function() {

    var dataSource = new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1.guid != r2.guid,
        sectionHeaderHasChanged: (s1, s2) => s1 !== s2
    });

    return {
        dataSource: dataSource,
        itemsList: this.getItemsList()
    };
},

getItemsList: function() {
    var userRef = usersRef.child("5019e705-0-29f09e520b7e");
    var itemsListRef = userRef.child("items_list");
    var itemsList;

    itemsListRef.on('value', (snap) => {
        itemsList = snap.val();
        return itemsList;     
    });
},

Upvotes: 1

Views: 545

Answers (1)

omarjmh
omarjmh

Reputation: 13888

You will need to use one of the React life cycle methods to handle async calls:

Check out the docs HERE

  componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  },

Upvotes: 1

Related Questions