I have this reactjs function to get data from firebase. The problem is the postsArray. It inside foreach has the objects, outside it is null.
I add postsArray globally.
Any ideas why the return is null?
postsRef.on('value', function(snapshot) {
setPosts(prevPosts => {
snapshot.forEach((subChild) => {
var value = subChild.val();
value = value.postID;
var post = firebase.database().ref('/posts/' + value);
post.on('value', function(snapshot2) {
postsArray = snapshot2.val();
console.log(postsArray); // HAS THE VALUE
});
console.log(postsArray); // NO VALUE HERE.
});
return [...prevPosts, ...Object.keys(postsArray).reverse().map(key => ({
key: key, ...postsArray[key]
}))];