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();
}
);
}