How do I seed a database when a user first uses my app?

Right now, I’m using a service I wrote to query an array of objects for my app. I would like to move this data to a SQL database. How do I set up my app to only create a table and insert my records and then save them in local storage on the first usage? Is there a “if table doesn’t exist” then “create table and add records” solution I can use?

Are you doing a local WebSql Database or key value pair for objects?

Right now, my data is just an array of JS objects. Going to move over to a local sqlite database.

I might be missing some complexity to your use case, but what you explained has a simple solution. Read from an Ionic Storage field named ‘firstInitializationComplete’ and store true there once it is complete. That way, if you read from it and it comes back falsy (eg null), you know the initialization hasn’t been done yet. You can do this in one command by starting with an Observable that reads the initialization status and then uses switchMap to read the full data either from Storage or the remote database.

Edit: pseudocode:

`this.data: Observable<Array<DataType>> = readInitStatus().switchMap(status => 
                                             { if (status) { return readFromStorage(); } 
                                               else { return readFromRemoteDatabase(); }
2 Likes

Such a simple and easy solution. Thanks a lot!