Gene
Gene

Reputation: 2218

ionic 2 local storage unable to set retrieved value to variable

I am trying to set the value retrieved from .get function into a variable declared outside but unable to do so.

var dt;
//retrieve
this.local.get('didTutorial').then((value) => {
  alert(value);
   dt = value;
})

console.log("Local Storage value: "+dt);

I'm able to get "true" for the alert, but getting "undefined" for the console.log that is printing outside of the function.

enter image description here enter image description here

One workaround is that I can put all my remaining codes into the ".then function" , but that would be very messy.

Update(Solution):

As per ionic api (http://ionicframework.com/docs/v2/api/platform/storage/LocalStorage/) , they use .get to retrieve values.

Since using promises has it's own limitations, by using the following:

 constructor(navController) {
     this.navController = navController;
     this.local = new Storage(LocalStorage);
 }

and getItem function,

localStorage.getItem('didTutorial')

You will be able to retrieve it without having to put everything into the callback method.

Upvotes: 3

Views: 4340

Answers (1)

Steven Petryk
Steven Petryk

Reputation: 683

Reading from your localStorage wrapper in this case is asynchronous, which means that the callback passed to this.local.get gets called after your call to console.log. Try placing console.log inside your callback; it should work then:

// retrieve
this.local.get('didTutorial').then((value) => {
  alert(value)
  var dt = value
  console.log("Local Storage value:", dt)
})

Also, you'll notice that I changed your console.log call arguments. That's because console.log accepts 1 or more parameters, and formats them much more nicely when you pass them in instead of concatenating them. Just a pro tip.

Upvotes: 6

Related Questions