Search code examples
javascriptangulartypescriptionic-frameworkcordova-nativestorage

Ionic native storage : storage.getItem() does not work


I am using ionic native storage to store some data. When i store and retrieve the data using setItem() and getItem() it works perfectly. But when i assign a value retrieved by getItem() in then block. it does not work outside the block.

showDetails(name: string) {
    this.stg.getItem(name).then(data => {
      console.log(data);
      
      this.pathName = data.name;
      this.type = data.type;
      this.positions = JSON.parse(data.positions);
      
      console.log(this.positions);
      
    });

    console.log(this.pathName + " " + this.type);
  }

When i print the data in the console i got the result and also i got the result when i print a single value inside then block but the last console.log shows to me undefined undefined.


Solution

  • It appears as though getItem returns a Promise as can be seen in the documentation. This means that this.pathName will only be set in the callback you are providing to then. If this is asynchronous then by the time your undefined line is run the then callback has not been called and thus no value has been set. This is one of the gotchas to async programming.

    A better approach would be to put all of your logic inside the callback:

    showDetails(name: string) {
        // get item could be async so do not assume your callback will be run immediately
        this.stg.getItem(name).then(data => {
          console.log(data);
    
          this.pathName = data.name;
          this.type = data.type;
          this.positions = JSON.parse(data.positions);
    
          console.log(this.positions);
    
          // values now been set
          console.log(this.pathName + " " + this.type);
        });
    
        // at this point no values have been set as the callback has not been called
        console.log(this.pathName + " " + this.type); // so this line is undefined
      }