Infinite loop with ionChange on ion-toggle

I have a toggle switch that subscribes a user to notifications on the backend.
When they turn the ion-toggle on, I go register them on the server. If anything fails, I turn the toggle back “off” programmatically in the component.

This triggers the ionChange event which unsubscribes on the server. If this fails, it turns the toggle back “on” programmatically.

This behavior is similar to iOS when you turn something like WiFi Calling or iMessage on, iOS sometimes does the neat little spinner next to the toggle to let the user know something is being “confirmed” on the backend.

There’s probably a combination of changing the event to maybe ionBlur or changing ngModel bindings but I can’t figure it out.

<ion-toggle
            color="danger"
            [(ngModel)]="villageCheckinNotifications"
            (ionChange)="toggleVillageCheckinsNotifications()"
          ></ion-toggle>
    console.log('changed value to: ', this.villageCheckinNotifications);
    if (this.villageCheckinNotifications) {
      this.notificationSvc.subscribeVillageCheckinNotifications().then(
        () => {
          // this.villageCheckinNotifications can stay true. accurately reflects state
        },
        (err) => {
          console.error('Error setting notifications: ', err);
          alert(
            'Error setting notifications. Please try resetting ReVillage Notification permissions in your phones Settings.'
          );
          // failed to configure so we need to reset UI
          this.villageCheckinNotifications = false;
        }
      );
    } else {
      this.notificationSvc.unsubscribeVillageCheckinNotifications().then(
        () => {
          // this.villageCheckinNotifications can stay true. accurately reflects state
        },
        (err) => {
          console.error('Error setting notifications: ', err);
          alert(
            'Error setting notifications. Please try resetting ReVillage Notification permissions in your phones Settings.'
          );
          // failed to configure so we need to reset UI
          this.villageCheckinNotifications = true;
        }
      );
    }
  }

Anyone smarter than me able to figure this out? :pray:t3:

Yep, and his name is @jasonwaters.

2 Likes