Ionic Storage and SQLite


#1

Hey guys,

so basically i’m having a real headache trying to get ionic storage module, and SQLite working correctly, i’m relatively new to Ionic and have been struggling to understand the structure a little bit.

i’ve managed to create a schema for an SQLite database that i want to implement onto a device although i’m not even sure where i’d have to place the .db file in the project file structure.

I have installed the relevant modules for storage use as per documentation here

However, i’m struggling to find decent examples of how to implement this code correctly (saving data, and calling it back and printing it out).

sorry for being a noob at this :sweat:.

in pseudo code, this is the scenario i want to achieve:

  1. person registers a user account in app that stores locally on the device.
  2. registration button is clicked. and triggers a (click)=“register(firstname, lastname, dob, password, email)”; where the code for register would look something like:
import { Storage } from '@ionic-storage';


constructor (private storage: Storage, [...]){}

register(firstname: string, lastname: string, dob: string, password: string, email:string): void {
  this.storage.set('firstname', firstname).then( ()=> { 
   this.storage.set('lastname', lastname).then(()=> {
    [...]
  } ).catch((e)=>{
   JSON.stringify(e)
   }); 
}

if any of that makes sense… if someone could point me into the right direction that would awesome; or if they have the SQLite equivalent then that would be awesome too.

Kind Regards.


#2

Some heuristics to make your life with Ionic Storage considerably less painful:

The Prime Directive: the only thing it should be used for is a “message-in-a-bottle” scenario where you have something now that you want to tell the next time the app is launched.

From which follows two important corollaries:

  • Only read from Storage once, at app launch (or whenever the relevant data is first needed)
  • You are free to write optimistically. If you want to worry about errors, fine, but you don’t need to chain and return set Promises.

Incidentally, if you are going to care about set returns, Promise.all is more idiomatic than cascading then chains.

So if we’re only allowed to read from Storage once, then how do I communicate new user information from one page to another in one running instance of my app? Via a service provider that exposes an Observable of user information. All places in the app that care about it can subscribe to it and always receive the latest data.