using async and await to avoid receiving 0 when accessing the array length of objects

Currently, my task involves searching for data in localStorage, then pushing this data (objects) to an array. However, when attempting to loop through this array of objects, I encounter an issue where the length is 0. I understand that I need to use async/await, but I am struggling to grasp how it functions.

this.afAuth.authState.subscribe(user => {

  if (user) {

    this.Uid = user.uid;

    this.storage.get(this.Uid ).then((val) => {

      this.CaloriesChartData = JSON.parse(val);

      if (this.CaloriesChartData != null) {

        this.CaloriesChartData = Object.keys(this.CaloriesChartData).map(key => ({ type: key, value: this.CaloriesChartData[key] }));

        this.CaloriesChartDataLength = this.CaloriesChartData.length;

        for (let i = 0; i < this.CaloriesChartDataLength; i++) {

          this.CaloriesArray.push(this.CaloriesChartData[i].value);

        }

      }
      console.log(this.CaloriesArray);
      console.log(this.CaloriesArray.length);

    });`

Upon inspection, I notice that the array is displayed as empty [], but expands when examined. The length is also shown as 0.

Answer №1

this.storage.get(this.Uid ) retrieves a Promise, which requires waiting. To use it, you must include

await this.storage.get(this.Uid )
. If you wish to store the returned value and avoid a Promise chain with async await, you can do so by creating a constant like
const data = await this.storage.get(this.Uid )
. Now you can work with the data instead of val. Since await can only be used within an async function, you need to update your arrow function to be async as well:

this.afAuth.authState.subscribe(async user => {

Putting it all together:

this.afAuth.authState.subscribe(async user => {

  if (user) {

    this.Uid = user.uid;

    const data = await this.storage.get(this.Uid );

    this.CaloriesChartData = JSON.parse(data);

    if (this.CaloriesChartData != null) {

      ...

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

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

Angular 5's data display glitch

Whenever I scroll down a page with a large amount of data, there is a delay in rendering the data into HTML which results in a white screen for a few seconds. Is there a solution to fix this issue? Link to issue I am experiencing HTML binding code snippe ...

Tips for integrating dynamic external components into Angular applications

I have encountered an issue with my Angular application. My goal is to create an Angular application written in TypeScript and built with (aot). The objective is to create a user dashboard with various widgets, each widget being an Angular component. Wh ...

Having difficulties in executing the user interface of a ReactJS-built application

Upon opening an existing project in Visual Studio Code, I discovered that the front end of the system was developed using "React". However, I faced a challenge in running the project and viewing its interfaces without any HTML files. I proceeded to execut ...

Failure to Apply Angular Conditional Class

What is the reason for test-abc not being included? <div class="abc" [class.test-abc]="true"></div> I successfully implemented it with this syntax: [ngClass]="{'foo': true, 'abc': true}" ...

"Effortlessly sending emails using the power of Angular 7 and SpringBoot

One of the challenges I'm facing is sending emails with SpringBoot using hardcoded data successfully. However, I am encountering an error 500 when attempting to retrieve data from my Angular form and call the API with that data. Can someone pinpoint ...

How to use the route.navigate() method in Angular 9 to open a URL in a new tab with a query string

When a button is clicked within a table in our application, I have to open a new tab with details of a specific record from the table. Currently, the code I am using navigates to a new URL and uses resolvers to fetch data from the backend on the new page. ...

Troubleshooting: Difficulty with Angular 2 TypeScript interface array functionality

Currently, I am developing an Angular 2 application where I aim to showcase messages by utilizing an interface and storing all the messages in an array. Below is a snippet of my TypeScript component that highlights this functionality: export class ChatCom ...

When you hover over the button, it seamlessly transitions to a

Previously, my button component was styled like this and it functioned properly: <Button component={Link} to={link} style={{ background: '#6c74cc', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 ...

Apply a class using [ngClass] based on an HTML condition within the local scope

In the past, I have utilized [ngClass] to assign classes based on the Boolean value of a variable in the JavaScript/TypeScript. However, I am now curious if it is achievable to apply [ngClass] based on a local HTML boolean value instead? For example: < ...

The service.subscribe function in Angular's Component Constructor is not functioning properly after the update

There are two components in my project, a parent and child component, and I am using a shared service to transfer data between them. The structure of the Service Class is as follows: export class AddItemDataTransferService { // Observable string sourc ...

Issue: NG04002 encountered post migration from Angular to Angular Universal

Having recently created a new Angular app and converted it to Angular Universal, I encountered an issue when running the project using npm run dev:ssr. The error displayed in the terminal is as follows: ERROR Error: Uncaught (in promise): Error: NG04002 Er ...

What strategies work well when it comes to developing translation files in Angular?

Currently, I am involved in a front-end project using Angular. For translation implementation, I am looking for the most effective approach to creating translation files. Instead of having a file per language, I am considering creating a translation file f ...

Using Jest and TypeScript to mock the return value of react-oidc-context

For our project, we utilize react-oidc-context to handle user authentication using oidc-client-ts under the hood. The useAuth function provided by react-oidc-context gives us access to important information such as isAuthenticated, isLoading, and the auth ...

How do I find the location of /typings when upgrading from version 0.x to 1.x?

As I develop an Angular 2 app using TypeScript, I have been following the guidance found in the 5 Min Quickstart guide. Recently, the npm typings package was updated from version 0.x to 1.x. Following the instructions on the official website, I deleted the ...

tips for obtaining the highest value among multiple keys within an array

How can I find the maximum value among multiple keys in an array? I previously attempted to find the maximum values for just three keys. getMaxValuefromkeys(values: any[], key1: string, key2: string, key3: string) { var val1 = Math.max.apply(Math, v ...

What steps can I take to concentrate on a particular mat-tab?

<mat-tab-group mat-stretch-tabs #tabGroup (focusChange)="tabChanged($event)" [selectedIndex]="0"> <mat-tab label="DATOS EXPEDIENTE"> <div class="example-large-box mat-elevation-z4"> <app-informe-expediente></app ...

Loading an entity from a service within an *ngFor loop: A step-by-step guide

Suppose I have a scenario where I need to display a list of students in Angular2. The data is fetched from a java backend using a service, and the fields are: id name age field universityId However, when displaying this data on my webpage, I want to sho ...

Input for Shared Component with routerLink

I'm looking to develop a shared component featuring a button that, upon clicking, redirects the user to a specified location. I want the consumer of the component to be able to define the route. How can I make this happen? My current idea is to set t ...

How can I prevent an element from gaining focus after opening a NgbModal?

In the template, I am using a ngForm which is passed as an argument to open a NgbModal: <form #optionsForm="ngForm" noValidate (ngSubmit)="saveOptions()" id="optionsForm"> <div class="modal-body"> <div class="form-group"> < ...