AnaCS
AnaCS

Reputation: 1011

Check if Storage is Empty Ionic 4 Storage plugin

I am fairly new to Angular/TypeSript/Ionic 4 so this may be a bi silly but I am using the Ionic Storage plugin, , that you can find in this page "https://ionicframework.com/docs/building/storage". And I am running into my fair share of troubles. The documentation is clear but too simple.

I need to check if my storage is empty and also see the content of my storage.

First, I tried going about it through the length, expecting it to return a number but with this code on the service :

getLenght(){
    return this.storage.length().then((res) => {
      return res;
    });
}

and this code on my page I get a object result:

   storageLength : any; // it would give me error as a Number
clearStorage() {
    this.dataStorageService.clear();
    this.storageLength = this.dataStorageService.getLenght(); // returns object promise
    alert(JSON.stringify(this.storageLength)); 
//{"__zone_symbol__state":null,"__zone_symbol__value":[]}

then I tried this instead but can't even run this, because of the error :

this.storage.get("qrCodeData").then( this.storage.get("qrCodeData") =>{}).catch(err=>{
    console.log("Your data don't exist and returns error in catch: " + JSON.stringify(err);
    });

error is "Argument of type 'Promise' is not assignable to parameter of type '(value: any) => any'. Type 'Promise' provides no match for the signature '(value: any): any'"

So not sure how to verify if the storage is emtpy, since I am running into all sort of problems, what am I missing here?

Upvotes: 3

Views: 3346

Answers (2)

BRass
BRass

Reputation: 3838

It is unclear exactly what you are storing, or exactly what you are trying to achieve. That said, dealing with the promise info returned from this Storage module is a lot cleaner if you use async/await in my opinion. An example is below.

let qrInfo = await this.getQrCodeData();
console.log(`Here is the result: ${qrInfo}`);  

...

async getQrCodeData(): Promise<string> {    
    await this.storage.ready();
    let qrCodeInfo = await this.storage.get("qrCodeData");
    return (qrCodeInfo) ? JSON.stringify(qrCodeInfo) : "";
}

Upvotes: 1

Sam
Sam

Reputation: 1139

You can try something like this :

getLength() { 
 return new Promise(resolve => {
      this.storage.get('qrCodeData').then((data) => {
        if(data){
          resolve(data);
        }    
      });    
    })    
} 

And if the data is empty, data will be undefined so you can check it.

Upvotes: 4

Related Questions