The for loop displays only the most recent data fetched from Firebase

When using a for loop to retrieve a user's progress, I encounter an issue.

In Typescript:

this.userProgress = af.object('/UserProgress/' + this.currentUser + '/', { preserveSnapshot: true });

    this.userProgress.subscribe(snapshots => {
        snapshots.forEach(snapshot => {
            this.userScores.push(snapshot.val());
        });
        console.log(this.userScores);

        // Set the loop condition to i<=8 because there are 9 quizzes in total. This means this.userScores.length -1
        for(var i=0; i <= 8; i++){
            if (this.userScores.length == i) {
                this.scores = [{
                    None: "Nothing Recorded"
                }];
                console.log("Nothing");
            }

            else if (this.userScores.length >= i) {
                this.scores = [{
                    Chapter:this.userScores[i].Chapter_Quiz,
                    QuizNo:this.userScores[i].Quiz,
                    Score:this.userScores[i].Score,
                }];
                console.log("With Scores");
            }
        }

    });

Initially, it will check if the userScores[] length is less than 0 or greater than or equal to 0. If no score exists for that quiz, it will display "Nothing Recorded". Otherwise, it will display the score.

In HTML:

<ion-card>

<ion-list *ngFor="let score of scores">
  <ion-card-header>
    {{score.Chapter}}
  </ion-card-header>

  <button ion-item *ngIf="scores.length < 0">
    <ion-icon name="planet" item-start></ion-icon>
    {{score.None}}
  </button>

  <button ion-item *ngIf="scores.length >= 0">
    <ion-icon name="planet" item-start></ion-icon>
    {{score.Score}}
  </button>

</ion-list>

I'm encountering an issue where only the last record is being displayed. What am I doing wrong?

https://i.sstatic.net/zCg3x.png

Desired Output:

If finished with the 1st quiz:

1st: Score
2nd: Nothing Recorded
3rd: Nothing Recorded
....

if no score at all:
1st: Nothing Recorded
2nd: Nothing Recorded
....

Answer №1

Make sure to update the this.scores variable correctly by using this.scores.push in each iteration of the loop to store data from previous quizzes.

Adjust the for-loop condition to i < this.userScores.length based on the array's length.

Modify the ngIf statement in the HTML to verify the existence of score.Score. If it is not present, there is no score recorded.

Answer №2

Based on your code, it appears that the condition this.userScores.length = 9 is always greater than the loop index i, which ranges from 0 to 8. Therefore, during each iteration of the loop, the last block (else if block) will be executed. Since you are not dynamically modifying or adding elements to the this.scores array, but simply assigning values to the object itself (without changing the array index for this.scores or appending to the existing list), the value at the current index of this.userScores[i] is stored in this.scores each time. By the end of the final iteration, the value of this.userScores[8] will be the only value in this.scores, resulting in a list with a length of 1.

Do you follow?

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

"Encountering a 400 Error While Attempting to Edit Requests in NodeJS/A

Currently, I am building an application using Ionic/Angular with a NodeJS backend. Within this project, I have created an update form that allows users to modify or delete a specific row. While the deletion function is working fine, I am facing some challe ...

Steps for creating an Angular project and deploying it to the server

After integrating Angular Universal into my project, I noticed that two new files called 'browser' and 'server' were generated during the build process. However, I am unsure of how to properly upload these new files to the server compar ...

Firebase Issue in Next JS Authentication Flow: Unconfirmed Email Causes "auth/email-already-in-use" Error to Trigger

I have encountered a perplexing issue while setting up user registration with Firebase Authentication in my Next.js application. The problem arises when I try to register a new user with an unverified email address. Instead of following the correct flow to ...

Creating mock objects with Jest

I am currently delving into the world of jest testing. Here is a snippet from an implementation class I'm working with: import { ExternalObject } from 'external-library'; export class MyClass { public createInstance(settings : ISettings) ...

Matching TypeScript search field names with column names

Seeking ways to create an API that allows admins to search for users in the database using various fields. // Define allowed search fields type SearchFieldType = 'name' | 'memberNo' | 'email' | 'companyName'; const ...

What sets Interface apart from InstanceType<typeof Class> when used as a variable type?

Let's take a look at an example implementation: HttpService.ts: export interface IHttpService { request(): Promise<any>; formPostRequest(): any; } export class HttpService implements IHttpService { public async request() { // Implem ...

Remove the array from the MySQL database

I have an array of strings called $url that contains many URLs. foreach ($array as $url){ $sql = "DELETE FROM url WHERE url='".$url."'"; if ($conn->query($sql) === TRUE) { echo "It's Deleted"; } } Currently, the code only displays a mes ...

Having trouble getting Ionic to install on node.js?

Encountering an issue with the installation of ionic framework: https://i.stack.imgur.com/o587q.png Operating system: Windows 10 Node.js version: 7.4 Npm version: 4.0.5 Npm installation completed successfully. Cordova installation also went smoothly. S ...

Using ngModel to Enhance Ionic Forms

I've encountered an issue with mapping a form to a model object. Once I include [[ngModel]] in the ion-input, the page fails to load without any errors. html <ion-input type="text" [(ngModel)]="personModel.username" formControlName="username" id= ...

Angular2 Uniqueness Validator: Ensuring Data Integrity

Within my Angular2 form field, I am trying to ensure that the inputted value does not already exist. The challenge lies in accessing instance members within my custom validator function, codeUnique(). Upon execution, "this" refers to either FormControl o ...

Encountering a POST 504 error while attempting to proxy an Angular application to a Node server

error message: Failed to connect to http://localhost:4200/api/user/login with a 504 Gateway Timeout error. Encountered this issue while attempting to set up a login feature in my Angular application and establish communication with the Express backend. Th ...

What is the best way to integrate a React component into an Angular project?

Struggling with integrating a React component into an Angular project and unable to make it work. I have a JavaScript file containing the React component that I want to use in Angular. Here's an example: React file... import React from "react"; c ...

I have exhausted all options trying to filter a 2D array in JavaScript

The 2D array provided is formatted as follows : [[ONE,1],[QUARTER,0.25],[QUARTER,0.25]] The desired output should be : [[ONE,1],[QUARTER,0.5]] An attempt was made using array.IndexOf but did not yield the expected result ONE,1,QUARTER,0.25,QUARTER,0.2 ...

choosing between different options within Angular reactive forms

I am attempting to create a select element with one option for each item in my classes array. Here is the TypeScript file: @Component({ selector: 'app-create-deck', templateUrl: './create-deck.component.html', styleUrls: [' ...

Deciding whether an array forms a chain of factors

I am curious about the reasons why this code is failing some of the tests provided. It deliberately avoids using any ES6 code. Here is the given prompt: *A factor chain can be defined as an array where each preceding element serves as a factor for the su ...

Issue: The React Hook "useDocumentOnce" is being called conditionally in this component. To ensure proper functionality, React Hooks must be called in the exact same order in every render of

While developing an application with NextJS, TailwindCSS, and Firebase, everything was functioning perfectly on my local host. However, upon deploying it to Vercel, I encountered the following error: 15:18 Error: React Hook "useRouter" is being called co ...

Is there a way to identify and count duplicate data-items within an array, and then showcase this information using a react view?

If we have an array like this: [{id: 1, name: "chocolate bar"}, {id:2, name: "Gummy worms"}, {id:3, name:"chocolate bar"}] Is there a way to show on the dom that we have "2 chocolate bars and 1 Gummy Worms"? ...

Challenges arise with dependencies during the installation of MUI

[insert image description here][1] I attempted to add mui styles and other components to my local machine, but encountered a dependency error. How can I resolve this issue? [1]: https://i.stack.imgur.com/gqxtS.png npm install @mui/styles npm ERR! code ERE ...

Issue NG8002: Unable to link to 'FormGroup' as it is not recognized as a property of 'form' in Angular 9

I recently created a brand new Angular 9 application with a submodule. Here are my app.modules.ts: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from & ...

Verify the content of each file in a bulk upload before transferring them to the server

I am facing an issue with a form that has 3 separate file input fields. I need to validate their MIME types individually before uploading them to the server. The first two should only allow MP3 files, while the last one should only allow JPEG files. Is th ...