How come Typescript is displaying a length of 0 even though the array contains 2 items?

Upon receiving a response from Firestore via onSnapshot, I retrieve 2 records and store them in an array called shop.

this.db.collection("Countries").doc("AU")
    .collection("cPostcode").doc(this.searchby)
    .collection(this.shop).where(how, '==', true)
    .onSnapshot(function (querySnapshot) {
        querySnapshot.forEach(function (doc) {
            shop.push(doc.data());
        })
    });
    console.log('shop.length', shop.length, 'Shop', shop);
    if (shop.length) {
        this.shopList = shop; .........

To check if any data has been returned, I use shop.length > 0, however, despite having 2 items in the array, shop.length shows as 0.

The output from the console log displays length: 2-

shop.length 0 shop []
    0:{ABN: "1", ACN: "2"}
    1:{ABN: "3", ACN: "4"}
    length:2
    __proto__:Array(0)

I attempted to include a flag within the forEach loop, but it goes out of scope causing issues with the "this.count" variable that I also tried. This has been an ongoing struggle for me over several days. Despite searching through Google for assistance and tips regarding Typescript, I have not found anyone else encountering this issue. What could I possibly be doing wrong?

Answer №1

To consistently obtain the length, it is crucial to ensure that you await a response.

  this.db.collection("Countries").doc("AU")
    .collection("cPostcode").doc(this.searchby)
    .collection(this.shop).where(how, '==', true)
    .onSnapshot((querySnapshot) => {
        // The data is available here
        querySnapshot.forEach((doc) => {
            shop.push(doc.data());
        });

        console.log('shop.length', shop.length, 'Shop', shop);

        // Hence, relying on shop.length should yield accurate results
        if (shop.length) {
            alert(shop.length);
        }
  });

Other options include utilizing promises or invoking a function once the result is obtained (instead of containing all the code within the callback function).

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

Is it impossible to Build your Angular project?

After updating my current project from Bootstrap 4 to Bootstrap 5, I encountered an issue where Jenkins is unable to build the project. The error message displayed is quite cryptic: An unhandled exception occurred: Cannot destructure property 'bold&ap ...

Problem: The variable "$" is not defined in angular datatables causing a ReferenceError

Trying to implement Paging and sorting in my table, but encountered an error even after following all the steps mentioned here: . Tried troubleshooting the issue with no success. Ensured that all dependencies were installed properly. Below is the compo ...

What type is the appropriate choice for this handler?

I´m struggling to select the right type for this particular function. It serves as an async handler for express js in a project that utilizes typescript and eslint for linting with specific rules. export function asyncHandler( handler: any ): (req: Requ ...

Pictures are shown using the "text/html" layout

I'm having trouble identifying the error and have decided to carefully examine both the client and server code. It seems likely that there is a bug somewhere in Rails. The issue revolves around the photos being displayed in text/html format. Here&apos ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Display a loading spinner while refreshing a list

Currently, I am in the process of developing an app using React Native. My goal is to display information (text) below my CalendarList based on data stored in an array. One of the properties in the array is the date. To achieve this, I have created a filte ...

What is the best way to retrieve all values in a PHP array?

Struggling to generate multiple new pages using a template where placeholders are replaced with values from arrays? It seems like the page creation is successful for a specific array index, but the goal is to create pages for all values in the arrays and n ...

Creating an asynchronous reducer using ngrx: A step-by-step guide

Exploring the realm of Angular, I am delving into the creation of an asynchronous reducer to handle API calls within my application. The ultimate aim is to fetch files from an API whenever the loadFiles action is activated. In order to achieve this, I dev ...

The FormGroup is experiencing issues with the functionality of the Submit button

I've been working on creating a FormGroup, but I've encountered an issue with the submit button not functioning as expected. The component in question is named create. Any idea what could be causing this problem? create.component.html ...

Angular component communication issue - emitter malfunctioning

Angular 4 Event emitter not functioning as expected despite following a tutorial for implementation. I am open to alternative solutions if available. Here is the code snippet for the transmitter component: .HTML <nav class="navbar navbar-toggleable-m ...

What is the correct way to start a typed Object in TypeScript/Angular?

As I delve into the world of Angular and TypeScript, I am faced with a dilemma regarding how to initialize an object before receiving data from an API request. Take for instance my model: //order.model.ts export class Order { constructor(public id: num ...

How to remove specific elements in an array using Matlab

Suppose we have an array a=[1 2 3 4 5 6 7 8 9 10]; and the task is to remove every 2 consecutive numbers starting from 3. The resulting array should be a=[1 4 7 10]; Is there a way to achieve this without using a for loop? Additionally, is there a me ...

Is it possible to create a sync function that includes a subscription to an observable?

Consider the following code snippet: observableMethod(): Observably { ... Return of([1, 2, 3]); } notObservableMethod(): integer { Let myVal; if (isOM) { this.observableMethod().pipe( first() ).subscribe( val => myVal = val; }); } else { myVal = thi ...

Add a npm module without type definitions

I am currently utilizing Typescript version 2.1 and facing an issue with installing an npm package called 'reactable' that lacks typings. When attempting to import the package using import * as Reactable from 'reactable', Typescript di ...

Design a personalized table inspired by the functionalities of primeng table

We previously utilized the p-table from primeng in our project. Now, our goal is to create a custom table component. I am looking to develop a custom table that resembles the one found at https://www.primefaces.org/primeng/#/table The table needs to incl ...

What is the best way to find a specific element within an array in Hive?

A table has been created using Hive with the fields listed below: ID BIGINT, MSISDN STRING, DAY TINYINT, MONTH TINYINT, YEAR INT, GENDER TINYINT, RELATIONSHIPSTATUS TINYINT, EDUCATION STRING, LIKES_AND_PREFERENCES STRING Data was inserted into this ta ...

Struggling to make the transition from JavaScript to TypeScript in Ionic 2

I recently updated the file extensions for my application files, including app/app.js. Error: Cannot find module 'app/app.js' from 'app_folder' The error message doesn't specify which file I need to locate to resolve the issue. ...

Incorrect type declarations in Typescript navigation.push in React Native cause unexpected behavior

Currently in my react native application, I have integrated @react-navigation/native-stack. However, the following line of code is causing an error: navigation.push('ScreenName', {myParam}); The error message reads as follows: TS2345: Argument ...

The OrderBy Pipe in Angular 4 fails to sort correctly when the name of the item being sorted

How can I sort names ending with numbers using a custom pipe? I have successfully implemented a custom pipe for sorting and it is working as expected. $Apple fruit -symbol 1Apple fruit -numbers Apple fruit -alphabetically However, the custom pip ...

In order to resolve the issue in nextjs 13 where the argument is of type 'any[] | null' and cannot be assigned to the parameter of type 'SetStateAction<never[]>', a potential solution may involve explicitly checking for null values

My current project uses Next.js 13 and is based on the Supabase database. I am attempting to fetch data from Supabase and assign it to a variable using useState, but encountering the following error: Argument of type 'any[] | null' is not assigna ...