Search code examples
ionic-frameworkionic4capacitor

ionic 4 capacitor storage get not working properly


Recently I moved from Cordova to capacitor storage API. And I am having a very strange issue. At page1 I am setting 4 values to local storage, but when I access these values on another page, one value is getting displayed as null.

I tried many approaches but value user_id is always null.

I made sure value is getting stored in local storage.

I am also attaching images of console.log after setting and retrieving values from local storage

storage.service.ts

 async set(key: string, value: any): Promise<any> {


    if(value == null || value == undefined) {
      console.log("dont'do")
    }
    else {

      try { 
        await Storage.set({
          key: key,
          value: value
        });

        return true;
      } catch (reason) {
          console.log(reason);
          return false;
      }
    }

  }
  // to get a key/value pair
  async get(key: string): Promise<any> {
  try {

    const result = await Storage.get({ key: key });
    console.log('storageGET: ' + key + ': ' + result.value);
    if (result != null) {
    return result.value;
    }
    else {
      console.log("null from service")
      return null;
    }

  } catch (reason) {
  console.log(reason);
  return null;
  }
  }

page1.ts

                this.storageService.set('user_id',data[i].id ).then(val => console.log(val))
                this.storageService.set('email', data[i].email).then(val => console.log(val))

                this.storageService.set('phone_number', data[i].mobile_no).then(val => console.log(val))
                this.storageService.set('firebase_uid', data[i].firebase_uid).then(val => console.log(val))

page2.ts

    this.storageService.get('user_id').then(val => console.log(val))
    this.storageService.get('email').then(val => console.log(val))
    this.storageService.get('phone_number').then(val => console.log(val))
    this.storageService.get('firebase_uid').then(val => console.log(val))

Console.log after setting values

enter image description here

console.log after retrieving local storage values

enter image description here


Solution

  • For everyone who needs it, unlike Cordova capacitor get API doesn't support numbers. So you have to convert it into string while setting into the storage only using JSON.stringify(value)

    example :

    await Storage.set({
          key: 'key',
          value: JSON.stringify(value)
        });