[SOLVED] LocalStorage after navCtrl.push

Hello,

In a page I’m setting data with LocalStorage. Immediately afterwards there is a redirect to a page.
In this second page (called “HomePage”), I’m getting data with LocalStorage, but doesn’t work: the second time from first to second page works.

But Why doesn’t work the first time?

    setTown(name) {
        this.localStorage.setData(name);
        this.redirectToHome();
    }

    redirectToHome(){
        this.navCtrl.push(HomePage);
    }

setTown(name) is called from a link in the first page in this way:

<ion-item (click)="setTown('Milan')">
...

Hi,

First, do you really you a method call setData? Isn’t the method just set?

Then, about your question, the problem could maybe be resolved using the promise respectively waiting for the set promise to be resolved, like

this.localStorage.set('myData', name).then(() => {
       this.redirectHome();
});

Thanks. So I simplified.
But It doesn’t work :frowning:
It works only the second time. :frowning:

        this.storage.set('myData', name).then(() => {
            this.redirectToHome();
        });

Mmmmh … could you

1 Add tappable (outside button or a it’s a good practice to add tappable to avoid 300ms seconds delay on click)

<ion-item (click)="setTown('Milan')" tappable>

2 Did you debug your method setTown(name) or added a console.log(name) to see how many times this method is triggered and what values are passed

3 How does HomePage looks like respectively where and how are you reading your value this.localStorage.get('myData')?

With “tappable” nothing to do.

Console.log returns
SET: milan
GET: turin (this is my previous choice)

When I press again another city:
SET: new york
GET: milan (the previous setting).

Goddamn ;(

Having the same issue with local storage. Only works the second time. Pretty puzzled as to why a simple Promise implementation could fail :confused:

You mean Ionic Storage? Storage isn’t ready the first time. Wrap your set inside storage.ready() and you’ll be ok.

Like?

 this.storage.ready().then(() => {
     this.storage.set('myData', name).then(() => {
        this.redirectToHome();
    });
});

this.storage.ready().then …

typing mistake (edited my post), morning coffee in progress :wink:

Yes, that looks fine.

1 Like

Ok.
With console.log all is ok.

this.storage.get('myData').then((val) => {
            console.log('Your city is', val);
});

Perhaps I have a problem to fetch value out of Promise.

Solved !!! Thanks for all. Your advices has been precious.

getLocalCity() {
        this.storage.get('myData').then((val) => {
            console.log('Your city is', val);
            this.loadHome(val);
        });
}

loadHome(value) {
        this.city = value;
}
1 Like