How come the variable consistently returns as undefined when using the '.find' method?

I can't figure out why my variable keeps returning undefined.

The issue I'm facing is that the 'schoolAndGradeLevelId' always comes back as undefined... I'm attempting to create a function that pushes student information to a variable, which will then be used to send the data to my API in order to create these students in the database. Any assistance would be greatly appreciated!

  public onFileSelected(files: Array<File>): void {
    if (files.length === 1) {
      this.file = files[0];
      this.loadFile();
      this.fileError = null;
    } else {
      this.file = null;
      this.fileError = 'Please select only one file';
    }
  }

  private fetchShcoolAndGradeLevelId(
    schoolName: string,
    gradeLevelName: string
  ): void {
    const query = this.queriesHandler.handle(
      new GetSchoolAndGradeLevelIdByNameQuery(schoolName, gradeLevelName)
    );
    query.subscribe({
      next: (res) => {
        this.schoolAndGradeLevelIds.push({
          ...res.data[0],
          schoolName,
          gradeLevelName,
        });
      },
    });
  }

  private loadFile(): void {
    let fileReader = new FileReader();
    fileReader.readAsBinaryString(this.file);
    fileReader.onload = (e) => {
      const excel = <string>fileReader.result;
      const rawStudents = parseImportedStudents(excel);
      rawStudents.forEach((student) => {
        let schoolAndGradeLevelId = this.schoolAndGradeLevelIds.find(
          (s) =>
            s.schoolName == student.schoolName &&
            s.gradeLevelName == student.gradeLevelName
        );
        if (!schoolAndGradeLevelId) {
          this.fetchShcoolAndGradeLevelId(
            student.schoolName,
            student.gradeLevelName
          );
          schoolAndGradeLevelId = this.schoolAndGradeLevelIds.find(
            (s) =>
              s.schoolName == student.schoolName &&
              s.gradeLevelName == student.gradeLevelName
          );
        }
        this.students.push({
          studentName: student.studentName,
          gradeLevelName: student.gradeLevelName,
          schoolName: student.schoolName,
          documentNumber: student.documentNumber,
          birthDate: student.birthDate,
          schoolId: schoolAndGradeLevelId?.schoolId,
          gradeLevelId: schoolAndGradeLevelId?.gradeLevelId,
        });
      });
    };
  }

  public onSave(): void {
    const data: ICreateMultipleStudentsRequest = {
      students: this.students.map((student) => {
        return {
          studentName: student.studentName,
          gradeLevelName: student.gradeLevelName,
          schoolName: student.schoolName,
          schoolId: student.schoolId,
          gradeLevelId: student.gradeLevelId,
          documentNumber: student.documentNumber,
          birthDate: student.birthDate,
        };
      }),
    };
    const command = new CreateMultipleStudentsCommand(data);
    this.commandsHandler.handle(command).subscribe(
      () => {
        this.toast.showSuccess('Students imported successfully');
        this.hideSpinner();
        this.dialog.hide();
        this.studentsImported.emit();
      },
      (err) => {
        this.toast.showError(err.error?.errorMessage);
        this.hideSpinner();
      }
    );
  }

Answer №1

To tackle this issue, I followed these steps:

public loadFile(): void {
let fileReader = new FileReader();
fileReader.readAsBinaryString(this.file);
fileReader.onload = (e) => {
  const excel = <string>fileReader.result;
  const rawStudents = parseImportedStudents(excel);
  rawStudents.forEach((student) => {
    this.students.push({
      studentName: student.studentName,
      gradeLevelName: student.gradeLevelName,
      schoolName: student.schoolName,
      documentNumber: student.documentNumber,
      birthDate: student.birthDate,
    });
  });
};
fileReader.onloadend = (s) => {
  this.students.forEach((student) => {
    let schoolAndGradeLevelId = this.schoolAndGradeLevelIds.find(
      (s) =>
        s.schoolName == student.schoolName &&
        s.gradeLevelName == student.gradeLevelName
    );
    if (!schoolAndGradeLevelId) {
      const query = this.queriesHandler.handle(
        new GetSchoolAndGradeLevelIdByNameQuery(
          student.schoolName,
          student.gradeLevelName
        )
      );
      query.subscribe({
        next: (res) => {
          this.schoolAndGradeLevelIds.push({
            ...res.data[0],
            schoolName: student.schoolName,
            gradeLevelName: student.gradeLevelName,
          });
          student.schoolId = res.data[0]?.schoolId;
          student.gradeLevelId = res.data[0]?.gradeLevelId;    
        },
      });
    } else {
      student.schoolId = schoolAndGradeLevelId?.schoolId;
      student.gradeLevelId = schoolAndGradeLevelId?.gradeLevelId;
    }
  });
};

}

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

There is an error occurring in Angular 9 when trying to implement a search filter for an object array with heterogeneous types

Trying to search through an array of objects using key-value pairs, but encountering an error in the console: core.js:5873 ERROR TypeError: obj[key].includes is not a function a = [ { id: 0, name: "xyz", grade: "x", frade: [ { name: "Paul", ...

What are some recommended guidelines for structuring an app that utilizes ngrx?

Structure 1 reducers index.ts //Combining all the reducers in one file user.reducer.ts product.reducer.ts actions index.ts //Grouping all actions in a single file user.action.ts product.action.ts effects index.ts //Merging differe ...

Obtain the filter criteria within the user interface of a Kendo grid

My Kendo grid looks like this: <kendo-grid [data]="gridData" [pageSize]="state.take" [skip]="state.skip" [sort]="state.sort" [filter]="state.filter" filterable="menu" (dataStateChange)="dataStateChange($event)" > In the ...

The color of the active background in Bootstrap 4 navbar

When a link is active in a Bootstrap 3 navbar, the background color of the link changes to indicate that it is the active link. This feature seems to be missing in Bootstrap 4. Is there a way to achieve this without overriding the active class? Below is a ...

When using Angularfire, the function to switch the type from snapshotChanges will consistently return the value as "value"

At this moment, when I use the Angularfire extension to call the following code: this.db.doc(path).snapshotChanges(); Angularfire always retrieves a DocumentSnapshot with a type that is consistently "value", regardless of the actual change type. Is there ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

multer failing to upload files using the default example

I am encountering difficulties with getting my code to function properly and I am not receiving any errors from multer. I have thoroughly double-checked everywhere for potential mistakes, but I am still stuck. Any assistance would be greatly appreciated. ...

Leverage arguments as properties within Angular components

Looking for a way to convert a string into an object property in Angular. For example: getErrorMessage(error_type) { return this.userForm.controls.{error_type}.hasError('required') ? 'You must enter a value' : ''; } getE ...

The Angular4 router.navigate function appears to be unresponsive and fails to perform any actions

I have implemented conditional navigation based on the customer's role in the system. Here is an example of how it works: this.GetQuickStartStatus() .subscribe(data => { if(data.isActive){ ...

Choose an option from the dropdown menu

I am facing a challenge with filtering data on a select element due to an overwhelming amount of options. Here is how I attempted to implement it: <mat-form-field> <mat-select placeholder="Unit.." (change)="onTabChange(element, $event.valu ...

The correlation between methods in programming languages

Can a class or object be created with type constraints between methods? abstract class Example<T>{ abstract methodOne(): T abstract methodTwo (arg: T):any } I am looking to ensure that the argument of methodTwo is the same type as the return ty ...

What are the potential reasons behind an Uncaught TypeError arising from an Object Prototype in the AOT build, but not in the development environment?

I've successfully created an Angular application that works flawlessly in the development environment. However, I recently transferred it to a sandbox server and after running ng build with the necessary parameters for base-href and environment, I enc ...

Is there a way to access a child component's method from the parent component using ref in Vue3?

I am encountering an issue while attempting to call the child method from the parent component in vue3 using the ref method. Unfortunately, an error is being thrown. Uncaught TypeError: addNewPaper.value?.savePaper is not a function Displayed below is m ...

Extract and process all the data from the JSON array using TypeScript

Given a JSON array as shown above, the task is to extract all the values from the array and create a new array of arrays. The challenge is to achieve this without using any model files in Typescript, and the method to do so is not clear. Assistance in re ...

Using Angular to transmit data to a transcluded component

Is it possible to have a video-uploader component where users can upload one or multiple videos, with the ability to choose from three different view options: Seperate - In progress videos and uploaded videos are displayed in separate tables. Combine ...

What is the best way to ensure that the HTML and CSS code exported from Figma is responsive

After exporting a Figma design to Angular code, I've encountered challenges in ensuring responsiveness, largely due to the extensive codebase. Media queries have proven ineffective as the majority of the code is written with (px) units and there are c ...

Steps to initiate a PDF file download when a button is clicked using Angular 6

I need assistance with downloading the .pdf file when clicking a button. Below is the code I am currently using: downloadMyFile() { const link = document.createElement('a'); link.setAttribute('target', '_blank&apos ...

Encountering issues during the installation of node modules

An error log is displayed below: 1027 error gyp verb check python checking for Python executable "python2" in the PATH 1027 error gyp verb `which` failed Error: not found: python2 1027 error gyp verb `which` failed at getNotFoundError ...

Which specific files do I have to edit in order for Laravel to acknowledge a new data type?

Currently, I am honing my skills in Laravel by working on a Laravel Breeze application. One task that I have set for myself is to incorporate a postal code field into the existing User model, including the registration form. To tackle this challenge, I dec ...

Angular - Showcasing Nested Objects in JSON

I am experimenting with using angular ngFor to iterate through this data: Link: Although I can successfully retrieve the data by subscribing to it, I encounter an issue when trying to display attributes that contain objects. The output shows as [object O ...