user3802348
user3802348

Reputation: 2592

React native trouble calling function within another function?

in my React-native app I am trying to call another function within my listenForItems function, but keep getting the error this.populateArray is not a function. In 'this.populateArray(solutions)', this.populateArray is undefined. I do this in other classes and it's working, but for some reason it's not working here. Is there anything I'm missing?

populateArray: function(solutions) {
    var completed = [];
    var inProgress;

    for (var i = 0; i < solutions.length; i++ ) {
        if (solutions[i].completed == 0) {
            inProgress = solutions[i].id;
        }
        else {
            completed.push(solutions[i].id);
        }
    }
},  

listenForItems: function(cluesRef) {

    var solutions = [];
    userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){
        var solution = snap.val();
        for (var i = 0; i < solution.length; i++) {
            if (solution[0].hunt_id == 0) {
                solutions.push(solution[0]);
            }
        }
        this.populateArray(solutions);
    });
},

Upvotes: 1

Views: 655

Answers (1)

agenthunt
agenthunt

Reputation: 8678

The classic this scope issue of javascript. Google will help with better understanding. In short, the word "this" inside a function refers to that function. In this example it refers the anonymous function (callback) that you use in userSolutionsRef.orderByChild. There are many ways to solve this. You can use ES6(ES2015) arrow functions in which case it becomes something like

userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', (snap) => {
    var solution = snap.val();
    for (var i = 0; i < solution.length; i++) {
        if (solution[0].hunt_id == 0) {
            solutions.push(solution[0]);
        }
    }
    this.populateArray(solutions);
});

or es5 solution

var that = this;
userSolutionsRef.orderByChild('user_id').startAt(0).endAt(0).once('value', function(snap){
        var solution = snap.val();
        for (var i = 0; i < solution.length; i++) {
            if (solution[0].hunt_id == 0) {
                solutions.push(solution[0]);
            }
        }
        that.populateArray(solutions);
    });

Upvotes: 3

Related Questions