Get data and store locally in storage.get

Hi everyone im having difficulty in storing the data from inside the storage.get method to a local variable: this is the code:

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, NavParams, ViewController } from ‘ionic-angular’;
import { Storage } from ‘@ionic/storage’;

@IonicPage()
@Component({
selector: ‘page-profileother’,
templateUrl: ‘profileother.html’,
})
export class ProfileotherPage {
id: any;
fname: any;
lname: any;

constructor(public navCtrl: NavController, public navParams: NavParams, public viewCtrl: ViewController, private storage: Storage) {

this.getName();

}

ionViewDidLoad() {
}

getname(){
this.storage.get(‘profile’).then((val) => {
this.lname = val.lname;
});
console.log(this.lname); //will not return the value(‘Reid’)but will return ‘undefined’
}

}

No you’re not. You’re having difficulty attempting to access it in the wrong place. Move your console.log inside the then block.

use this code.
I hope this will help you out.

use undefined or null check. Sometimes storage gives you undefined or null value in first attempt

this.storage.get('profile').then(val =>{
if(val != null){
console.log("Value in Storage : ", val)
}
else{
console.log("Null or Undefined value err :", val)
}},err=>{
console.log("Storage error : ", err)
})

Thanks mr. @ShehramTahir ill do this :slight_smile:

Thanks @rapropos ill do this :slight_smile:

For more details, see this post. From what you’ve said so far, it seems that you have one of the second set of situations here.

The code is running asynchronously, which means the data hasn’t even been set by the time you try to log the data. This is why all manipulations and usage of the stored data need be done inside the Promise, or inside the .then

okay thank you sir :slight_smile:

1 Like

yes sir, thank you sir, now i know :slight_smile:

1 Like