Cannot read property 'gender' of undefined at Object.eval [as updateDirectives]

Viewed 763

I'm creating a social media app and I'm not sure why I keep getting this error when navigating to a new user's settings page. The problem is that there's no values in the database for these fields.

Here is the code.

  userSettings: IUserSettings = {
    gender: null,
    drinks: null,
    smoking: null,
    ageRange: this.ageRange,
    distance: this.distance,
    notifications: true,
    dateOfBirth: null
  };


  ngOnInit() {
    console.log('settings', this.userSettings)
    this.afAuth.authState.subscribe(user => {
      this.getDataSvc.getUserFromFirebase(user.uid)
        .then((data) => {
          this.userSettings = data.data().userSettings;
        }).catch((error) => {
          console.log('errr', error);

        });
    });
  }
      <ion-button expand="block" color="success" style="margin-bottom: 20px;">
        <ion-icon size="large" name="transgender-outline" padding-left="20px"></ion-icon>
        <ion-select id="gender" name="gender" placeholder="Gender" required #genderField="ngModel"
          [(ngModel)]="userSettings.gender" [class.field-error]="form.submitted && genderField.invalid">
          <ion-select-option>Female</ion-select-option>
          <ion-select-option>Male</ion-select-option>
          <ion-select-option>Other</ion-select-option>
          <ion-select-option>No Preference</ion-select-option>
        </ion-select>
      </ion-button>
      <div [hidden]="genderField.valid || genderField.untouched" class="alert alert-danger">
        Must select an option
      </div>

I initially thought I could just add a null check to [(ngModel)]="userSettings?.gender" but that doesn't work.

When I enter the settings page it just keeps displaying the same error:

ProfileSettingsPage.html:16 ERROR TypeError: Cannot read property 'gender' of undefined
    at Object.eval [as updateDirectives] (ProfileSettingsPage.html:17)
    at Object.debugUpdateDirectives [as updateDirectives] (core.js:45259)
    at checkAndUpdateView (core.js:44271)
    at callViewAction (core.js:44637)
    at execComponentViewsAction (core.js:44565)
    at checkAndUpdateView (core.js:44278)
    at callViewAction (core.js:44637)
    at execEmbeddedViewsAction (core.js:44594)
    at checkAndUpdateView (core.js:44272)
    at callViewAction (core.js:44637)

2 Answers

The error you are seeing is because the DOM elements are loaded even before you have your userSettings value. As mentioned by @robbieAreBest. You need to wrap the parent block in an *ngIf check for the userSettings.

Your ion-select doesn't know what userSettings are when loaded.

    <ion-button *ngIf="userSettings" expand="block" color="success" style="margin-bottom: 20px;">
            <ion-icon size="large" name="transgender-outline" padding-left="20px"></ion-icon>
            <ion-select id="gender" name="gender" placeholder="Gender" required #genderField="ngModel"
              [(ngModel)]="userSettings.gender" [class.field-error]="form.submitted && genderField.invalid">
              <ion-select-option>Female</ion-select-option>
              <ion-select-option>Male</ion-select-option>
              <ion-select-option>Other</ion-select-option>
              <ion-select-option>No Preference</ion-select-option>
            </ion-select>
          </ion-button>
<span *ngIf="!userSettings">Loading data...</span> // this is optional

So instead of using an object I used primitive types as my ngModel to resolve this issue.

 gender: string;
  drinks: string;
  smoking: string;
  notifications: boolean = true;

  userSettings: IUserSettings = {
    gender: null,
    drinks: null,
    smoking: null,
    ageRange: this.ageRange,
    distance: this.distance,
    notifications: true,
    dateOfBirth: null
  };

  validations_form: FormGroup;
  errorMessage: string = '';

  constructor(private router: Router,
    private dataSvc: DataService,
    private afAuth: AngularFireAuth,
    private getDataSvc: GetDataService,
  ) { }

  ngOnInit() {
    console.log('settings', this.userSettings)
    this.afAuth.authState.subscribe(user => {
      this.getDataSvc.getUserFromFirebase(user.uid)
        .then((data) => {
          this.gender = data.data().userSettings.gender,
            this.drinks = data.data().userSettings.drinks,
            this.ageRange = data.data().userSettings.ageRange,
            this.distance = data.data().userSettings.distance,
            this.notifications = data.data().userSettings.notifications
        }).catch((error) => {
          console.log('errr', error);
        });
    });
  }

  goToProfilePage() {
    this.router.navigateByUrl('tabs/profile');
  }

  savePersonalInfo(form) {
    console.log(form.valid);
    if (form.valid) {
      this.userSettings = {
        gender: form.value.gender,
        drinks: form.value.drinks,
        smoking: form.value.smoking,
        ageRange: this.ageRange,
        distance: this.distance,
        notifications: this.notifications,
        dateOfBirth: null
      };
      this.dataSvc.addUserSettings(this.userSettings).then(() => {
        this.goToProfilePage();
      }
      )
    }
    <ion-card >
      <ion-button  expand="block" color="success" style="margin-bottom: 20px;">
        <ion-icon size="large" name="transgender-outline" padding-left="20px"></ion-icon>
        <ion-select id="gender" name="gender" placeholder="Gender" required #genderField="ngModel"
          [(ngModel)]="gender" [class.field-error]="form.submitted && genderField.invalid">
          <ion-select-option>Female</ion-select-option>
          <ion-select-option>Male</ion-select-option>
          <ion-select-option>Other</ion-select-option>
          <ion-select-option>No Preference</ion-select-option>
        </ion-select>
      </ion-button >
      <div [hidden]="genderField.valid || genderField.untouched" class="alert alert-danger">
        Must select an option
      </div>

It works when I use primitive types in the HTML ngModel

Related