Ion Toggle is not saved - Storage (ionic)

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.