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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.