Storage.get returns null on init app

Hi, im using Storage module, my problem is when i try to get stored data on application init.
the first time no data is loaded, when i call a second time the same method ( " this.storeService.getUserData(); ") data is loaded well.

i have called my storage service on constructor of my homepage.ts, like this:

//Ready event is raised well, if i put a toast here it is shown
  this.plt.ready().then((readySource) => {
       this.dataUser= this.storeService.getUserData(); 
    });

in getUserData Method i have the folowing code:

getUserData(){
  this.getStoreduser(); 
  return JSON.parse(this.userData);
}

and in the StoreService class constructor i have:


//I have tried without storage.ready but is the same
this.storage.ready().then((readySource) => {
        this.getStoreduser();
 
      });

and the method getStoredUser:

async  getStoreduser(){
    await this.storage.get(this.KEY_USR).then(res=>{
       this.userData=res;

    },err=>{
      return null;
    });
   }

i dont know what is my problem, can you help me please?

Regards

First off, forget about the existence of async and await. They’re of dubious value to anybody IMHO, and are especially troublesome for those unfamiliar with asynchronous JavaScript.

Secondly, always declare types for return values of every function you write, and when you write things like getUserData or getStoredUser, always make them return something and only use the thing they return. Don’t ever rely on function side effects on external state. What I mean here is:

Do do this:

getUserData(): Promise<UserData> {...}
...
getUserData().then(userData => {...});

Don’t do this:

userData?: UserData;
getUserData(): void {
  this.userData = ???;
}
...
getUserData();
relyOn(this.userData);

Despite all the gyrations you’re attempting in getStoredUser, there is not and cannot be any guarantee external to that function as to when this.userData is reliable.

Thank you, it works now :slight_smile: .