Ionic 5 Native Storage Store and Retrieve Data Tutorial

Ionic 5 Angular native Storage tutorial; This comprehensive guide helps you ascertain how to store and retrieve data or information on a user’s device using Ionic native’s native storage and Cordova native storage plugin.

A native storage package is ideal for saving various types of information on the user device, and this information consists of a user profile, app settings, sessions, and many more. Fret not; native storage plugin covers all.

Apparently, ionic’s WebView memory is employed to store device information; this information doesn’t fade away even if the user clears the cache and closes the app.

This tutorial will explain how to use Native storage in the Ionic 5 app and save the data in key-value pair as a JSON object. You have to remember native mobile apps use SQLite databases for storage, whereas PWA (progressive web apps) don’t require native storage if used on the user’s browser. In that case, you may go with IndexedDB or localStorage for storage.

Ionic 5 Angular Native Storage Example

  • Step 1: Install or Update Ionic CLI
  • Step 2: Create New Ionic Angular Project
  • Step 3: Install Native Storage Plugin
  • Step 4: Update NativeStorage in AppModule
  • Step 5: How to Use Native Storage in Ionic
  • Step 6: Ionic Native Storage Methods
  • Step 7: Test Ionic App

Install or Update Ionic CLI

Make sure the latest version of the Ionic CLI is properly installed. The Ionic CLI tool can be added globally with npm on your system:

npm install -g @ionic/cli

Create Ionic Angular Project

You can use below command to create a new working Ionic Angular app:

ionic start native-storage-demo blank --type=angular

Get into the project directory:

cd native-storage-demo

Install Native Storage Plugin

Open terminal, type mentioned below commands to install native storage plugin through Cordova and Ionic native.

ionic cordova plugin add cordova-plugin-nativestorage

npm install @ionic-native/native-storage

npm i @ionic-native/core

Update NativeStorage in AppModule

Next, Import NativeStorage module from the from ‘@ionic-native/native-storage/ngx’ in AppModule file.

Update code in app.module.ts file:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';

// storage module
import { NativeStorage } from '@ionic-native/native-storage/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    NativeStorage,
    { 
      provide: RouteReuseStrategy, 
      useClass: IonicRouteStrategy 
    }
  ],
  bootstrap: [AppComponent],
})

export class AppModule {}

How to Use Native Storage in Ionic

To access the storage methods, we first import the NativeStorage module profoundly at the top of your ionic page, thereafter inject the NativeStorage inside the constructor() method.

We show you how to use native storage on the Home page. However, you may use it on any page or component.

import { Component } from '@angular/core';
import { NativeStorage } from '@ionic-native/native-storage/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(
    private storage: NativeStorage
  ) {}

  // Native storage methods can be accessed below ...

}

Ionic Native Storage Methods

In this step, we will show you how to Set, Get, Get All, Remove and Clear data or information in Ionic native storage.

Update app.component.ts file:

import { Component } from '@angular/core';
import { NativeStorage } from '@ionic-native/native-storage/ngx';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})

export class HomePage {

  constructor(
    private storage: NativeStorage
  ) {}

  // Native storage methods can be accessed below ...

  setData(){
    this.storage.setItem('mcu', { 
      property: 'Winter Soldier', 
      anotherProperty: 'Falcon' 
     }).then(
        (res) => alert(JSON.stringify(res)),
        err => alert(JSON.stringify(err))
      );
  }

  getData() {
    this.storage.getItem('mcu')
      .then(
        res => alert(JSON.stringify(res)),
        err => alert(JSON.stringify(err))
      );    
  }

  getAllData(){
    this.storage.keys()
      .then(
        res => alert(JSON.stringify(res)),
        err => alert(JSON.stringify(err))
      );    
  }

  removeData() {
    this.storage.remove('mcu')
      .then(
        res => alert(JSON.stringify(res)),
        err => alert(JSON.stringify(err))
      );
  }

  clearData() {
    this.storage.clear()
      .then(
        res => alert(JSON.stringify(res)),
        err => alert(JSON.stringify(err))
      );
  }  

}

Create some buttons using the ion-button attribute and bind them to click events, and pass the custom methods as per the associated task.

Update app.component.html file:

<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Native Storage in Ionic
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-button color="danger" expand="block" (click)="setData()">Set Data</ion-button>

  <ion-button color="success" expand="block" (click)="getData()">Get Data</ion-button>

  <ion-button color="tertiary" expand="block" (click)="getAllData()">Get All Data</ion-button>

  <ion-button color="warning" expand="block" (click)="removeData()">Remove Key</ion-button>

  <ion-button color="dark" expand="block" (click)="clearData()">Clear</ion-button>
</ion-content>

Test Ionic App

To run an app on the emulator, you require to add the platform:

# iOS
ionic cordova platform add ios

# Android
ionic cordova platform add android

Thereafter, prepare the runnable build:

# iOS
ionic cordova build ios

# Android
ionic cordova build android

Eventually, start the app on the device:

# iOS
ionic cordova run ios -l

# Android
ionic cordova run android -l

Summary

In the final analysis, we would say Ionic native storage is best not just by its useful and handy methods but because of its subtle debugging that can be done even on browsers. Consequently, we have concluded the Ionic native storage tutorial and comprehended the storage methods such as Set, Get, Get All, Remove and Clear. We hope it will help you understood the local native storage concept in ionic.