ark
ark

Reputation: 849

Iterating and modifying Firebase array causes undefined

EDIT: it seems that value[i].extrainfoimage is only undefined within imageRef.child("-JlSvEAw......

I've read through the documentation twice so far and still haven't been able to figure this one out.

Basically I load some data from firebase and set it as an array. I iterate through that array and intend to replace some properties, as I iterate, with data I get from other places in my Firebase DB. However everytime I go to replace the properties I get

"Uncaught TypeError: Cannot set property 'extrainfoimage' of undefined"

This is my code:

var questionsRef = new Firebase("https://XX.firebaseio.com/Questions");
var imageRef = new Firebase("https://XX.firebaseio.com/Images");

//get the first 6 items
var query = questionsRef.orderByChild('date_time_asked').limitToFirst(6);
//get them as a firebase array promise
$scope.questions = $firebaseArray(query);
//wait for it to load
$scope.questions.$loaded().then(function (value) {
//iterate through
for (i = 0; i < value.length; i++) {
    //check if there is data to be replaced
    if (value[i].extrainfoimage) {
           //if there is fetch it from firebase and replace
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value",function(data){
                        value[i].extrainfoimage = data.val();
                    });
                }
            }
        })

Upvotes: 1

Views: 414

Answers (1)

eladcon
eladcon

Reputation: 5825

Possibly its becuase the last item in value doesn't have extrainfoimage. Because your set for value[i].extrainfoimage is async, it doesn't capture the correct i value, and therefore fails when it is executing.

Try to wrap it in a IIFE:

for (i = 0; i < value.length; i++) {
    //check if there is data to be replaced
    if (value[i].extrainfoimage) {
       (function(curr) {
           //if there is fetch it from firebase and replace
           imageRef.child("-JlSvEAwu5-WZJkOE_b/image").once("value",function(data){
                    value[curr].extrainfoimage = data.val();
           });
        })(i);
    }
}

Upvotes: 1

Related Questions