Ionic 4 - Save and Retrieve Data using Native storage and SQLite
Tags: ionic, storage, data, retrieve
Published: 2020-03-25 20:35:07

<main role="main"><article class=" u-minHeight100vhOffset65 u-overflowHidden postArticle postArticle--full is-withAccentColors" lang="en"><div class="postArticle-content js-postField js-notesSource editable" id="editor_6" g_editable="true" role="textbox" contenteditable="true" data-default-value="Title
Tell your story…" spellcheck="false"><section name="0427" class="section section--body section--first section--last"><div class="section-divider"><hr class="section-divider"></div><div class="section-content"><div class="section-inner sectionLayout--insetColumn"><p name="a97d" class="graf graf--p graf-after--figure">This post is all about saving data locally in your cool new app. In this post, you will learn</p><ul class="postList"><li name="df63" class="graf graf--li graf-after--p">How to implement <code class="markup--code markup--li-code">cordova-sqlite-storage </code>in our app.</li><li name="039a" class="graf graf--li graf-after--li">How to integrate <code class="markup--code markup--li-code">native-storage</code> into an ionic app.</li></ul><p name="00df" class="graf graf--p graf-after--li">Before start, first you will need an ionic app to start with, hence you can follow <a href="https://enappd.com/blog/how-to-create-an-ionic-4-app-for-beginners/13"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank"><strong class="markup--strong markup--p-strong">how to create an ionic app for beginners</strong></a> and start after that from here.</p><h3 name="c185" class="graf graf--h3 graf-after--p">1. Storage&#8202;—&#8202;What and&nbsp;why?</h3><p name="3796" class="graf graf--p graf-after--h3">Storage is an easy way to store key/value pairs and JSON objects. Storage uses a variety of storage engines underneath, picking the best one available depending on the platform.</p><p name="8624" class="graf graf--p graf-after--p">When running in a native app context, Storage will prioritize using SQLite, as it’s one of the most stable and widely used file-based databases, and avoids some of the pitfalls of things like local storage and IndexedDB, such as the OS deciding to clear out such data in low disk-space situations.</p><p name="fd0e" class="graf graf--p graf-after--p">As every application needs their data to store in local storage or cache for fast loading or for any purpose, we have a nice solution for that in ionic as @ionic/storage.</p><p name="40dc" class="graf graf--p graf-after--p">To start with first execute the following command in your terminal:</p><p name="b851" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">ionic cordova plugin add cordova-sqlite-storage</code></p><p name="df6f" class="graf graf--p graf-after--p">Next, install the package (comes by default for Ionic apps &gt; Ionic V1):</p><p name="bb42" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">npm install --save @ionic/storage</code></p><p name="7c4f" class="graf graf--p graf-after--p">Next, add it to the imports list in your <code class="markup--code markup--p-code">NgModule</code> declaration (for example, in <code class="markup--code markup--p-code">src/app/app.module.ts</code>):</p><pre name="f7b5" class="graf graf--pre graf-after--p is-selected"><code class="markup--code markup--pre-code">import { IonicStorageModule } from '@ionic/storage';<br>@NgModule({<br>  declarations: [<br>    // ...<br>  ],<br>  imports: [<br>    BrowserModule,<br>    IonicModule.forRoot(MyApp),<br>    IonicStorageModule.forRoot()<br>  ],<br>  bootstrap: [IonicApp],<br>  entryComponents: [<br>    // ...<br>  ],<br>  providers: [<br>    // ...<br>  ]<br>})<br>export class AppModule {}</code></pre><p name="2c74" class="graf graf--p graf-after--pre">Now create a service for ionic storage functions by executing this command:</p><p name="c673" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">ionic generate service storage</code></p><p name="d3ec" class="graf graf--p graf-after--p">Now in your generated storage service add the following codes to use wherever needed in the application:</p><pre name="c98b" class="graf graf--pre graf-after--p">import { Injectable } from '@angular/core';<br>import { Storage } from '@ionic/storage';<br>@Injectable({<br>providedIn: 'root'<br>})<br>export class StorageService {<br>constructor(public storage: Storage)<br>{ console.log('Your storage provider is working here !'); }<br>// set a key/value<br>async set(key: string, value: any): Promise&lt;any&gt; {<br>try {<br>const result = await this.storage.set(key, value);<br>console.log('set string in storage: ' + result);<br>return true;<br>} catch (reason) {<br>console.log(reason);<br>return false;<br>}<br>}<br>// to get a key/value pair<br>async get(key: string): Promise&lt;any&gt; {<br>try {<br>const result = await this.storage.get(key);<br>console.log('storageGET: ' + key + ': ' + result);<br>if (result != null) {<br>return result;<br>}<br>return null;<br>} catch (reason) {<br>console.log(reason);<br>return null;<br>}<br>}<br>// set a key/value object<br>async setObject(key: string, object: Object) {<br>try {<br>const result = await this.storage.set(key, JSON.stringify(object));<br>console.log('set Object in storage: ' + result);<br>return true;<br>} catch (reason) {<br>console.log(reason);<br>return false;<br>}<br>}<br>// get a key/value object<br>async getObject(key: string): Promise&lt;any&gt; {<br>try {<br>const result = await this.storage.get(key);<br>if (result != null) {<br>return JSON.parse(result);<br>}<br>return null;<br>} catch (reason) {<br>console.log(reason);<br>return null;<br>}<br>}<br>// remove a single key value:<br>remove(key: string) {<br>    this.storage.remove(key);<br>}<br>//  delete all data from your application:<br>clear() <br>{<br>   this.storage.clear();<br>}<br>}</pre><p name="22d5" class="graf graf--p graf-after--pre">Now create a page using the ionic command:</p><p name="e222" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">ionic generate page storagedemo</code></p><p name="37de" class="graf graf--p graf-after--p">In <code class="markup--code markup--p-code">storagedemo.page.ts</code> inject <code class="markup--code markup--p-code">storage</code> in constructor</p><p name="f5fd" class="graf graf--p graf-after--p"><code class="markup--code markup--p-code">constructor(public storageService: StorageService) { }</code></p><p name="dad0" class="graf graf--p graf-after--p">Now let’s save and get strings in your constructor. For simplicity, we’ll just output the result in the <strong class="markup--strong markup--p-strong">console</strong>.</p><p name="5c15" class="graf graf--p graf-after--p"><strong class="markup--strong markup--p-strong">i. Save String:</strong></p><pre name="3295" class="graf graf--pre graf-after--p">this.<code class="markup--code markup--pre-code">storageService</code>.set('user_name', 'Shadman').then(result =&gt; {<br>console.log('Data is saved');<br>}).catch(e =&gt; {<br>console.log("error: " + e);<br>});</pre><p name="98de" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">ii. Get String:</strong></p><pre name="f6cc" class="graf graf--pre graf-after--p">this.<code class="markup--code markup--pre-code">storageService</code>.get('user_name').then(result =&gt; {<br>if (result != null) {<br>console.log('Username: '+ result);<br>}<br>}).catch(e =&gt; {<br>console.log('error: '+ e);<br>// Handle errors here<br>});</pre><p name="030a" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">iii. Save an Object:</strong></p><pre name="f2e9" class="graf graf--pre graf-after--p">this.<code class="markup--code markup--pre-code">storageService</code>.setObject('person', {name : 'Shadman', age : 26});</pre><p name="d17a" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">iv. Get an Object:</strong></p><pre name="5e62" class="graf graf--pre graf-after--p">this.<code class="markup--code markup--pre-code">storageService</code>.getObject('person').then(result =&gt; {<br>if (result != null) {<br>console.log('Person: '+ result);<br>}<br>}).catch(e =&gt; {<br>console.log('error: ', e);<br>});</pre><p name="f00a" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">v. You can remove any value associated with the key:</strong></p><pre name="e444" class="graf graf--pre graf-after--p">this.storageService.remove('user_name');</pre><p name="24d7" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">vi. You can delete/clear all the data from your application:</strong></p><pre name="4ed6" class="graf graf--pre graf-after--p">this.storageService.clear();</pre><h3 name="f3e1" class="graf graf--h3 graf-after--pre">2. Ionic native-storage&#8202;—&#8202;What and&nbsp;Why?</h3><p name="0c29" class="graf graf--p graf-after--h3">This plugin is created because of the non-persistent property of LocalStorage in the WebView of Android and iOS. In iOS stored data from LocalStorage can be removed by the OS, when running out of memory.</p><p name="16ac" class="graf graf--p graf-after--p"><strong class="markup--strong markup--p-strong">When to use the plugin:</strong></p><ul class="postList"><li name="fe63" class="graf graf--li graf-after--p">Simple: Uniform and convenient way of organizing, storing, and accessing the data</li><li name="17ad" class="graf graf--li graf-after--li">Fast: Less than 1 millisecond to save or retrieve an object (in general)</li><li name="f5a3" class="graf graf--li graf-after--li">Persistence: Save data over multiple sessions, i.e. holds the data until the application is removed from the device</li><li name="6fd9" class="graf graf--li graf-after--li">Small data: Store small amounts of persistent data (less than a few hundred kilobytes)</li><li name="4105" class="graf graf--li graf-after--li">It is possible to store more than a few megabytes, but that’s not the intended usage of the plugin.</li></ul><p name="f9dc" class="graf graf--p graf-after--li"><strong class="markup--strong markup--p-strong">When not to use the plugin:</strong></p><ul class="postList"><li name="e78b" class="graf graf--li graf-after--p">Storing and retrieving files can be done by means of the <a href="https://github.com/apache/cordova-plugin-file"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">file plugin</a></li><li name="e50d" class="graf graf--li graf-after--li">For storing many objects please consider trying a database-based strategy, for instance: WebSQL and <a href="https://github.com/litehelpers/Cordova-sqlite-storage"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">SQLite plugin</a>.</li></ul><h3 name="d98a" class="graf graf--h3 graf-after--li"><a href="https://ionicframework.com/docs/native/native-storage#installation"  class="markup--anchor markup--h3-anchor" rel="noopener"    target="_blank">Installation</a>:</h3><p name="cf18" class="graf graf--p graf-after--h3">Execute the following command in your terminal:</p><pre name="cff0" class="graf graf--pre graf-after--p">ionic cordova plugin add cordova-plugin-nativestoragenpm install @ionic-native/native-storage</pre><p name="493b" class="graf graf--p graf-after--pre">After installation completes, import <code class="markup--code markup--p-code">NativeStorage </code>module in your <code class="markup--code markup--p-code">app.module.ts</code></p><pre name="521d" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">import { NativeStorage } from '@ionic/storage';<br>@NgModule({<br>  declarations: [<br>    // ...<br>  ],<br>  imports: [<br>    BrowserModule,<br>    IonicModule.forRoot(MyApp),<br>    NativeStorageModule.forRoot()<br>  ],<br>  bootstrap: [IonicApp],<br>  entryComponents: [<br>    // ...<br>  ],<br>  providers: [<br>    // ...<br>  ]<br>})<br>export class AppModule {}</code></pre><p name="c2b5" class="graf graf--p graf-after--pre">Now you are totally set to use this in your app’s components/pages as:</p><p name="25c3" class="graf graf--p graf-after--p"><strong class="markup--strong markup--p-strong">Storing values</strong></p><pre name="fe65" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">this.nativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'})<br>  .then(<br>    () =&gt; console.log('Stored item!'),<br>    error =&gt; console.error('Error storing item', error)<br>  );</code></pre><p name="941a" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">Retrieving values</strong></p><pre name="46d2" class="graf graf--pre graf-after--p"><code class="markup--code markup--pre-code">this.nativeStorage.getItem('myitem')<br>  .then(<br>    data =&gt; console.log(data),<br>    error =&gt; console.error(error)<br>  );</code></pre><p name="4b43" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">Retrieving all keys</strong></p><pre name="aca1" class="graf graf--pre graf-after--p">storageService.keys().then(<br>data =&gt; console.log(data),<br>error =&gt;{console.log(error);}<br>);</pre><p name="c428" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">Removing values</strong></p><p name="85f3" class="graf graf--p graf-after--p">Removing a single variable:</p><pre name="d8b5" class="graf graf--pre graf-after--p">NativeStorage.remove("reference_to_value",&lt;success-callback&gt;, &lt;error-callback&gt;);</pre><p name="721b" class="graf graf--p graf-after--pre">Removing all stored variables:</p><pre name="877b" class="graf graf--pre graf-after--p">NativeStorage.clear(&lt;success-callback&gt;, &lt;error-callback&gt;);</pre><p name="20c3" class="graf graf--p graf-after--pre"><strong class="markup--strong markup--p-strong">iOS-specific features</strong></p><ul class="postList"><li name="fc9c" class="graf graf--li graf-after--p">App Groups (share data between apps) First the suite name must be provided before accessing and retrieving data.</li></ul><pre name="e62a" class="graf graf--pre graf-after--li">NativeStorage.initWithSuiteName("suitename");</pre><p name="9ba4" class="graf graf--p graf-after--pre">Now at last but not least, you’re all set to play with ionic/storage and ionic/native storage.</p><h3 name="82b6" class="graf graf--h3 graf-after--p">Conclusion:</h3><p name="1e41" class="graf graf--p graf-after--h3">In this post, we learned how to implement ionic SQLite-storage and ionic native-storage, we got to know the difference and the use of these two in ionic 4 application. I hope this post made your confusions clear that what is ionic-storage and why to use, as same for the native-storage.</p><h3 name="4da3" class="graf graf--h3 graf-after--p">NEED FREE IONIC 4 STARTERS?</h3><p name="eff2" class="graf graf--p graf-after--h3">You can also find free Ionic 4 starters on our website <a href="http://enappd.com/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">enappd.com</a></p><ul class="postList"><li name="2b12" class="graf graf--li graf-after--p"><a href="https://store.enappd.com/product/free-chat-themes-ionic4/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Free Chat Themes Starter for Ionic 4</a></li><li name="a4be" class="graf graf--li graf-after--li"><a href="https://store.enappd.com/product/ionic4-firebase-starter/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Free Ionic 4&#8202;—&#8202;Firebase Starter</a></li></ul><p name="2930" class="graf graf--p graf-after--li">You can also make your next awesome app using <a href="https://store.enappd.com/product/ionic-4-full-app/"  class="markup--anchor markup--p-anchor" rel="noopener"    target="_blank">Ionic 4 Full App</a></p><h3 name="28f8" class="graf graf--h3 graf-after--p">Next Steps</h3><p name="178a" class="graf graf--p graf-after--h3">Now that you have learned the implementation of SQLite-storage and native -storage for storing or caching values in Ionic 4, you can also try</p><ul class="postList"><li name="b8f3" class="graf graf--li graf-after--p"><a href="https://enappd.com/blog/spotify-like-music-in-ionic-4-apps/48/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Play Spotify style mucic in ionic 4.</a></li><li name="f32a" class="graf graf--li graf-after--li"><a href="https://enappd.com/blog/ionic-4-paypal-payment-integration-for-apps-and-pwa/16"  class="markup--anchor markup--li-anchor" rel="nofollow noopener noopener noopener noopener noopener noopener noopener noopener"    target="_blank">Ionic 4 PayPal payment integration&#8202;—&#8202;for Apps and PWA</a></li><li name="fc67" class="graf graf--li graf-after--li"><a href="https://enappd.com/blog/how-to-integrate-apple-pay-in-ionic-4-apps/21"  class="markup--anchor markup--li-anchor" rel="nofollow noopener noopener noopener noopener noopener noopener noopener noopener"    target="_blank">Ionic 4 Apple Pay integration</a></li><li name="b1fc" class="graf graf--li graf-after--li"><a href="https://enappd.com/blog/twitter-login-in-ionic-4-apps-using-firebase/24"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Twitter login in Ionic 4 with Firebase</a></li><li name="57fe" class="graf graf--li graf-after--li"><a href="https://enappd.com/blog/facebook-login-in-ionic-4-apps-using-firebase/25"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Facebook login in Ionic 4 with Firebase</a></li><li name="97f4" class="graf graf--li graf-after--li"><a href="https://enappd.com/blog/implement-google-vision-in-ionic-4/43/"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">How to implement google vision in Ionic 4</a></li><li name="34a6" class="graf graf--li graf-after--li"><a href="https://medium.com/enappd/qr-code-scanning-and-optical-character-recognition-ocr-in-ionic-4-95fd46be91dd"  class="markup--anchor markup--li-anchor"    target="_blank">QR Code and scanners</a> in Ionic 4 and</li><li name="de81" class="graf graf--li graf-after--li"><a href="https://medium.com/enappd/how-to-translate-in-ionic-4-globalization-internationalization-and-localization-31ec5807a8bc"  class="markup--anchor markup--li-anchor"    target="_blank">Translations in Ionic 4</a></li></ul><h3 name="f2a8" class="graf graf--h3 graf-after--li">References</h3><ul class="postList"><li name="bb4a" class="graf graf--li graf-after--h3 graf--trailing"><a href="https://ionicframework.com/docs"  class="markup--anchor markup--li-anchor" rel="noopener"    target="_blank">Ionic documentation</a></li></ul></div></div></section></div></article></main>