Search code examples
angularngrx-storengrx-effects

Angular 15 Ngrx store/effects


I tried for a while now and many different things but i just cant find a solution why this

  constructor(protected subjectService: SubjectsService,
              protected userService: UsersService,
              protected languageService: LanguageService,
              protected translate: TranslateService,
              protected gradeService: GradeService,
              private store: Store<{ subjectGrades: SubjectGrade[], subject: Subject[] }>) {

    if (this.userService.getLoggedInUser().admin) {
      this.displayedColumns = ['subject', 'avgGrade', 'actions'];
    }
    this.subjects$ = this.store.select('subject');
    this.subjectGrades$ = this.store.select('subjectGrades');
    this.updateSubjectsAndAVGGrades();
  }


  updateSubjectsAndAVGGrades(): void {
    this.subjects$
      .pipe(
        takeUntil(this.subscriptions),
        switchMap((subjects: Subject[]) => {
          this.subjects = subjects;
          console.log('subjects', subjects);
          return this.subjectGrades$.pipe(
            takeUntil(this.subscriptions),
            map((grades: SubjectGrade[]) => {
              return subjects.map(subject => {
                const subjectGrades = grades.filter(grade => grade.subject.id === subject.id);
                return this.gradeService.calculateAvgGrades(subjectGrades);
              });
            })
          );
        })
      )
      .subscribe((avgGrades: Grade[]) => {
        this.avgGrades = avgGrades;
      });
  }

somehow has a case where Grades or Subjects are undefined.

I just debugged for hours in my Reducer, Action, Effect all Data gets passed around perfectly. I load both initialstates in the AppComponent the initialstates are based on a http fetch from a backend.


Solution

  • Found the Problem it was because when i defined the state in the reducer it happened sometimes that because it was asynchronous that the data transferred was undefined so the array ended up being undefined. To solve this i added a check that if its undefined state turns into a empty Array.

    on(loadSubjectGradesSuccess, (state, {subjectGrades}) => {
        if (subjectGrades === undefined) return state;
        return subjectGrades;
      }),