Ionic Store return undefined from a provider function


#1

Hi everyone,
I have a problem with my project. I had created functions in provider:

stor(name:any,dat:any){
this.storage.set(name,dat);
}

read(key: any) {
this.storage.get(key).then((val) => {
return val;
});
}

When I call function read() in home.ts with console.log(this.myprovider.read(‘name’))
it shows me undefined.

When i put console.log in provider function it printed me a data from store, so It saves the data but can’t be used out of provider on my home.ts. Code:

read(key: any) {
this.storage.get(key).then((val) => {
console.log(val);
});
}

How can I fix this issue?


#2

The easiest and most robust way to “fix the issue” is to change your expectations for storage. It should be used for one and only one purpose: to deliver non-critical information that we know now to the next time the app is run.

Every part of that description matters, so do not use storage for:

  • communicating within a single app run
  • storing things that the app will be unable to launch without

If you sign on to these rules, then your stor is more or less fine (except it should return void and name should be string, not any). read, however, should look like this:

read(key: string): Promise<any> {
  return this.storage.get(key);
}

…leaving all the then() work to whoever calls read, which must happen only once, generally at application start time.


#3

Thank You so much man, for Your fast answering and Your method of answering me. You are great. I have just fixed It, so I can go further with my app. Thanks once more