JavaScript array does not support iteration

Last night, I encountered an unusual issue while working with a basic JavaScript array. In my React Native app connected to Firebase's real-time database through the SDK, I came across something unexpected.

Here's the piece of code:

    var app = this

    this.props.fb.auth().onAuthStateChanged(function(user) {
        if (user) {
            app.props.fb.database().ref('/users/' + user.uid + "/timeline").once('value').then(function(snapshot) {
                var posts = snapshot.val()
                return posts
            }).then((posts) => {                
                var statuses = [];
                for (i in posts) {

                    app.props.fb.database().ref('/posts/' + posts[i]).once('value').then(function(snapshot) {
                       statuses.push(snapshot.val())
                    });
                }

                console.log(statuses)
            })
        }

    });

The objective of the above code was to retrieve data from each user's timeline, loop through the posts on the timeline, and fetch post-specific data from posts. The extracted data was supposed to be added to the statuses array, which is then displayed using console.log at the end.

Upon checking the console, the following output appeared. https://i.sstatic.net/qWgh9.png

Strangely, until the array is expanded, its items are not visible in the console. Furthermore, when attempting to determine the length of the array, it returns 0, making it impossible to iterate over the elements within the array.

Could anyone point out what might be going wrong here?

Answer №1

If you have an iterable called posts, consider utilizing a form of q.all to efficiently handle multiple promises simultaneously. Once all promises are resolved, you can securely document the results and append them to the statuses array.

Here is a simplified example:

if (user) {
        app.props.fb.database().ref(`/users/${user.uid}/timeline`)
        .once('value')
        .then(snapshot => snapshot.val())
        .then(posts => {                
            const statuses = [];

            const promises = Object.keys(posts).map(key => {
                return app.props.fb.database().ref(`/posts/${posts[key]}`).once('value')
                    .then(snapshot => statuses.push(snapshot.val()));
            }

            return Promises.all(promises)
        })
        .then(() => console.log(statuses));
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize Laravel 8 and Vue Js to dynamically showcase retrieved data in input fields

I am facing a challenge with my Laravel 8 registration form using Vue js. Before submitting the form, I need to verify if the referring user exists in the database. If the user is found, I want to dynamically display their full name in an input field upon ...

Ways to update the content of a NodeList

When I execute this code in the console: document.querySelectorAll("a.pointer[title='Average']") It fetches a collection of Averages, each with displayed text on the page: <a class="pointer" title="Average" onclick="showScoretab(this)"> ...

What is the most effective way to transmit a sizeable JSON file to a server?

In my web.config file, I set the maxrequestlength to 10MB. However, there is a feature in my system that allows clients to import a .csv file that can potentially be larger than 10MB. As a result, I am looking for an efficient way to send a large json file ...

Showing commute time using Google Maps API v3

Is there a way to display the travel time immediately when opening Google Maps API v3? If you want to show the driving time as soon as the map is loaded, check out this example that demonstrates switching between travel modes. While it's easy to set ...

Display/Conceal a div using CSS in React JS/Redux

I've been working on a CSS toggle for a div with className toggling. My approach involves using redux to manage the boolean state. Using the redux chrome extension, I can see that the state is indeed changing but the div remains invisible. If you have ...

Generating unique identifiers for ng-model in AngularJS

Issue - ng-model is not generating dynamically. I have dynamic input boxes and I am attempting to create ng-model dynamically like test[1], test[2], etc. However, when inspecting the form with Firebug, all input elements only show - test[shiftnumber]. HT ...

Learn how to create an endless scrolling effect on a static webpage using only pure JavaScript

Looking to achieve an Infinite Page Scroll Effect similar to Twitter without relying on jQuery or any other library, using pure JavaScript. I'm new to JavaScript and need assistance with implementing this effect in search results displayed within a La ...

Using .htaccess for a 301 Redirect

I am currently working on setting up 301 redirects, and regardless of whether I implement the redirect in .htaccess or use a meta or javascript redirect, they all seem to be working. However, there is an issue where the old URL or directory is being append ...

Exploring the benefits of utilizing express-session for authentication management

I am currently in the process of creating a basic login application using express 4 and express-session. When setting up my code as follows: app.use(session({ store: new MongoStore({ db: 'sess' }), secret: 'Ninja Turtle', cookie ...

What could be the reason behind my Vue custom directives not functioning as expected?

I'm brand new to Vue and very inexperienced with custom directives. I'm attempting something basic, but it doesn't seem to be working correctly. Can someone please help me figure out what's wrong? Thank you in advance! I have created tw ...

I am having trouble getting my getColor() method to correctly change colors based on the data provided

When using a datatable, there are two columns: status and priority. The STATUS LIST includes OPEN or CLOSED, while the PRIORITY LIST includes HIGH, MODERATE, and LOW. So, if the status is open, it should be displayed in red color; if closed, then in green. ...

Sophisticated layering of partials and templates

I am facing a challenge in handling intricate nesting of templates (also known as partials) within an AngularJS application. To illustrate my predicament, I have created an image: As depicted, this application has the potential to become quite complex wi ...

The curious behavior of $viewContentLoaded in Angular

For my jQuery code, I wanted it to run immediately after the template view was loaded and the DOM was modified. To achieve this, I initially used the $viewContentLoaded event in my controller. $scope.$on('$viewContentLoaded', function(){ // ...

Exploring the differences between utilizing Node JS Express for server-side development and displaying console output to

Recently, I started delving into the world of node js and came across IBM's speech to text sample application (https://github.com/watson-developer-cloud/speech-to-text-nodejs). This app utilizes the express framework and showcases transcribed audio fr ...

Error: Unable to locate module '@mui/icons-material/FileDownload'

I have successfully installed both @material-ui/core and @material-ui/icons. Currently, I am attempting to import the icon "FileDownloadIcon" from Material icons. For installing "@material-ui/core", I used the following command: npm i ...

What is the approach for capturing system or website sound using JavaScript?

After creating an online drumkit and guitar player, I am now looking to enhance my website by adding a feature that allows users to record their sessions and download them. Since I am new to web development and familiar only with HTML, CSS, JavaScript, and ...

Spacing issues with inline-block elements when dealing with a large quantity of items

Currently, I am tackling the JS/jQuery Project for The Odin Project and I am confident that my solution is working exceptionally well. However, the issue I am facing is that when dealing with larger amounts of elements (around 40-45 in JSFiddle and 50-52 ...

Initializing arrays at the class scope in C++11

Having experience with Java and Ruby, I find coding simple tasks in C++ to be more challenging... I am looking to initialize an array in the constructor of a class with predetermined values that can be accessible to all methods within the class. It's ...

How to pass a data property as a function argument in Vue.js

Instead of using a few methods that are structured like this: showDiv1(){ this.showDiv1 = true }, showDiv2(){ this.showDiv2 = true } I am attempting to consolidate them into one method like so: showElements(...elementNames){ elementNames. ...

Game board in disarray due to an unexpected array exceeding its limits

In the code for a slightly more complex version of tic tac toe, there is a method that is causing an issue. Whenever the computer attempts to make a move, it triggers an array out of bounds -1 error. This is particularly perplexing because I have taken c ...