Ion Toggle is not saved - Storage (ionic)

Hi, I have a simple problem. I have a list of Toggles in my app. I need that when users check or uncheck Toggle, the changes are saved after the app is closed. I’m using StorageModule.

I used this code to add Storage:

ionic cordova plugin add cordova-sqlite-storage

Then I made the additions to my app.module.ts

my HTML:

<ion-toggle slot="end" color="secondary" [(ngModel)]="Ativar" (ionChange)="Toggle1()"></ion-toggle>

my TS:

import { Storage } from '@ionic/storage-angular';

export class Tab1Page {
 
 public Ativar : boolean;



 constructor(public alert: AlertController, public navCtrl: NavController, 
private storage: Storage) { }

 async Toggle1() {
     if(this.Ativar == true){
       this.storage.set('ativar', true);
     }
     if(this.Ativar == false){
       this.storage.set('ativar', false);
     }
     this.storage.get('ativar').then((data) => {
       this.Ativar = data;
   });
   };

I use the app emulator to run the app on my phone:

ionic cordova run android

When I make changes in Toggle and close the app, when I open it, the changes are not saved. I’ve been stuck at this stage for a long time. I just wish the toggle was saved. Can someone help me? I’m lost

Several things here.

  • SQLite is overkill for 90% of things I see people here wanting to put into storage. IndexedDB should be just fine, and easier to work with, because it works in desktop browsers as well.
  • Naming conventions are incredibly important for making readable code. Variables and properties: camelCase. Classes and interfaces: PascalCase.
  • Also best to try to avoid string literals unless they’re protected as part of TypeScript types, so declare a constant for “ativar”. Otherwise, I guarantee you’re going to spell it differently somewhere and spend hours wondering what’s going on.
  • Never interact directly with storage in pages. Do it only in services. This preserves separation of concerns and makes it much easier to refactor and add data-handling functionality later that you won’t know you need now.
  • Avoid async until you understand completely what it is and what it does.
  • What it isn’t is a Tardis that warps asynchronous action into behaving synchronously, so…
  • You have a race condition between your storage writes and reads.
  • The cleanest way I have found to avoid those is to only read from storage once per app run, at startup (or pause/resume, if you don’t think of those as causing a new “app run”).

This post has code for an idiom to manage distributing user profiles across an app. It can be adapted to do similar duty for your toggles.