0

Simpleish react question that is evading me for a second:

  readData: function(){
    var readFromCpDev1 = firebase.database().ref('environments/' + 'cp-dev1');
    var envUsersArray = [];
    readFromCpDev1.on('value', function(snapshot) {
      envUsersArray.push(snapshot.val())
      return envUsersArray;
    });
    console.log(envUsersArray, 'hey');
  },

anotherfunc: function(){
}

I have this function and I want to return envUsersArray and use it wherever. Obviously at the moment it is returning a blank array as the readData function is not in the scope of the snapshot function. How can I pass it down to the readData function and then use it inside another function such as anotherfunc

I know I probably need to call this. somewhere but the logic isn't quite coming to me at the mo

2
  • Is readFromCpDev1.on asynchronous? Commented Oct 26, 2016 at 10:41
  • @changed I believe so. at least according to my understanding from the firebase docs Commented Oct 26, 2016 at 10:42

2 Answers 2

1

I'd suggest using Promises.

  readData: function(){
    return new Promise(function(resolve) {
      var readFromCpDev1 = firebase.database().ref('environments/' + 'cp-dev1');
      var envUsersArray = [];
      readFromCpDev1.on('value', function(snapshot) {
        envUsersArray.push(snapshot.val())
        resolve(envUsersArray);
      });
    });
  },

  anotherfunc: function(){
    this.readData().then(function(arr) {
      //do stuff here
    });
  }
Sign up to request clarification or add additional context in comments.

Comments

0

You may return a promise that will resolve with value that is retrieved asynchronously:

  readData: function() {
    var readFromCpDev1 = firebase.database().ref('environments/' + 'cp-dev1');
    var envUsersArray = [];
      return new Promise(function(success) {
      readFromCpDev1.on('value', function(snapshot) {
        envUsersArray.push(snapshot.val())
        success(envUsersArray);
      }
    });
  },

  anotherfunc: function(){
   this.readData().then(function(result) {
     console.log(result);
   });
  }

1 Comment

It's actually same as what @Pavel Staselun answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.