The worm The worm - 1 month ago 7
Javascript Question

Passing an array to another function in ReactJS

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

Answer

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
    });
  }
Comments