0

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)
    });
user3802348
  • 2,502
  • 11
  • 36
  • 49
  • 3
    The array is not being cleared, it's just not populated yet when you log `NEWLIST 2`. The data is loaded asynchronously and your code is (luckily for the user) not waiting for the result. Your logging should show that by the order in which they appear: `NEWLIST 2` and only then `NEWLIST`. For a good explanation of this phenomenon, see http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Frank van Puffelen May 01 '16 at 15:21
  • 1
    [Why is my variable unaltered after I modify it inside of a function?](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) and [JavaScript closure inside loops](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Jonathan Lonowski May 01 '16 at 15:24

2 Answers2

1

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.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86
1

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

Prashant Agrawal
  • 660
  • 9
  • 24