Edupala

Comprehensive Full Stack Development Tutorial: Learn Ionic, Angular, React, React Native, and Node.js with JavaScript

Ionic capacitor storage

Ionic capacitor storage

The Ionic Capacitor storage API is a simple way to store the data without any relational database capabilities.  The Ionic capacitor allows us to create a PWA application. The Capacitor Storage API provides a key-value store for simple data, the value may be a simple string or a complex JSON Object.

Ionic Capacitor Storage works on Strings only. However, storing complex objects is easy: just JSON.stringify the object before calling set, then JSON. parse the value returned from the get.

Advantage of Ionic Capacitor Storage

Ionic Capacitor Storage API use different storage location based on the platform. When running an application on iOS this plugin will use UserDefaults and on Android SharedPreferences. Stored data is cleared if the app is uninstalled. Mobile OS’s may periodically clear data set in window.localStorage, so this API should be used instead of the window.localStorage. This API will fall back to using localStorage when running as a Progressive Web App.

Ionic capacitor storage stores data in key/value pairs, the value may be a simple string or a complex JSON Object.

Ionic capacitor storage

Setting up Ionic capacitor storage example project

To demonstrate the Ionic capacitor storage example, we had to flow certain steps to implement it.

Step 1:  Create a project and add Capacitor to our project.

ionic start storageApp blank --type=angular --capacitor
cd storageApp
npm install @capacitor/storage
npx cap sync

Step 2: Create a storage service.
We have created a local Storage service. , The storage class has a few methods of storage. set and storage. get method to set and retrieve the data. Create a folder called services and add the following code in the app/services/storage.service.ts file

import { Injectable } from '@angular/core';
import { Storage } from '@capacitor/storage';


@Injectable({
    providedIn: 'root'
})
export class StorageService {

    constructor() { }

    async setString(key: string, value: string) {
        await Storage.set({ key, value });
    }

    async getString(key: string): Promise<{ value: any }> {
        return (await Storage.get({ key }));
    }

    async setObject(key: string, value: any) {
        await Storage.set({ key, value: JSON.stringify(value) });
    }

    async getObject(key: string): Promise<{ value: any }> {
        const ret = await Storage.get({ key });
        return JSON.parse(ret.value);
    }


    async removeItem(key: string) {
        await Storage.remove({ key });
    }

    async clear() {
        await Storage.clear();
    }
}

Step 3:  Implementing storage activities 
Add the following code in the home.page.ts We have to import the storage service. We have three buttons to set, retrieve and clear storage data.

import { Component } from '@angular/core';
import { StorageService } from '../services/storage.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss']
})
export class HomePage {
  person = { name: '', country: ''};
  name: string;
  storageName: string;
  country: string;

  constructor(
    private storage: StorageService
  ) {}

  setStorage() {
    this.storage.setString('name', this.name);
    this.storage.setObject('person', {
      name: this.name,
      country: this.country
    });
  }

  getStorage() {
    this.storage.getString('name').then((data: any) => {
      if (data.value) {
        this.storageName = data.value;
      }
    });
    this.storage.getObject('person').then((data: any) => {
      this.person = data;
    });
  }

  clearStorage() {
    this.storage.clear();
  }

}

Step 4: Display storage date in the template and following code in home.page.html

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic 6 Capacitor Storage API
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content class="ion-padding">
  <ion-list>
    <ion-item>
      <ion-label position="floating">Enter Name</ion-label>
      <ion-input type="text" [(ngModel)]="name" placeholder="Enter name" required></ion-input>
    </ion-item>

    <ion-item>
      <ion-label position="floating">Country</ion-label>
      <ion-input type="text" [(ngModel)]="country" placeholder="Enter country" required></ion-input>
    </ion-item>

    <div class="ion-float-right">
      <ion-button (click)="setStorage()">Set storage data</ion-button>
      <ion-button color="tertiary" (click)="getStorage()">Get storage data</ion-button>
      <ion-button color="tertiary" (click)="clearStorage()">Clear storage</ion-button>
    </div>
  </ion-list>

  <ion-item>
    Get LocalStorage string name : {{ storageName }}
  </ion-item>
  <ion-item>
    Get LocalStorage JSON person :  {{ person?.name }} : {{ person?.country }}
  </ion-item>
</ion-content>

Check more information on ionic capacitor storage on official documentation.

Conclusion
We had completed our Ionic capacitor storage example using service. I hope you get some idea of how to use an Ionic storage capacitor.

Related posts

Ionic capacitor storage

5 thoughts on “Ionic capacitor storage

  1. when I close the application through the window manager and go back to the application it loses the data I saved, I would like a way to persist this data

  2. I try to follow your Tutorial, but already on Step 1: when I am doing “npx cap sync” I got the error “Could not find the web assets directory: ./www.” and I also do not have a directory “services” in the “app” folder.

    Any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top