user3802348
user3802348

Reputation: 2592

Array undefined outside of javascript function?

I've defined a function in React-Native that gets an object from Firebase and pushes its contents onto an array. However, although the array is being populated fine after my call to 'push', it is undefined at the end of the for loop. I have no idea why it's being cleared, as I'm defining the array outside of the for loop, so I thought I'd ask for an extra pair of eyes in case I'm missing anything.

    var newList = [];
    var arrayLength = userArray.length;
    for (var i = 0; i < arrayLength; i++) {

        var userRef = usersRef.child(userArray[i]);
        userRef.once('value', function(snap) {
            newList.push({
                name: snap.val().name,
                description: snap.val().description,
            });
            //this log statement prints out correct array
            console.log("NEWLIST" + newList[i]);
        });
        //but array is undefined here
        console.log("NEWLIST 2" + newList[i]);
    }
    this.setState({
        current: this.state.current.cloneWithRows(newList),
        past: this.state.past.cloneWithRows(oldList)
    });

Upvotes: 0

Views: 689

Answers (2)

Prashant Agrawal
Prashant Agrawal

Reputation: 670

The code looks fine but what I think might be happening here is that userRef.once() is an async call, and your outer console.log is getting executed first. And when the event triggers the callback your inner console.log() prints the value

Upvotes: 1

Robert Moskal
Robert Moskal

Reputation: 22553

Read up on JavaScript's asynchronous nature. The once function takes a callback. The console.log in the outer scope is executed before you push any items info your array.

Upvotes: 1

Related Questions