V. Aliosha
V. Aliosha

Reputation: 152

Ionic platform.exitApp() not saves localStorage

When I'm using platform.exitApp() the changes to localStorage I did right before execute exit are not saving.

Here is how I initiate it:

this.user.profileGetbyId(this.user.userdata.id)
                                .subscribe(res => {
                                    if(res && res.success) {

                                        localStorage.setItem('user', res.data);
                                        this.user.userdata = res.data;
                                        console.log(this.user.userdata);
                                        this.platform.exitApp();

                                        //temp decision
                                        // setTimeout(() => {
                                        //  this.platform.exitApp();
                                        // }, 500);

                                    }
                                })

In this way, before exit() initiates the console shows me that I have updated the user, but when I start app the next time I have the user that was before exit().

The next thing I tried was to call exit with a time delay, using setTimeout(). With this timeout the user saves correctly.

How do I keep the changes in right way without setTimeout() ?

Upvotes: 0

Views: 115

Answers (2)

Chaitanya Mankala
Chaitanya Mankala

Reputation: 1704

this.storage.set returns a promise, wait for it to resolve and do exit.

Here's the code

this.storage.set('user', res.data).then(data=>{
   this.user.userdata = res.data;
   this.platform.exitApp();
})

in localStorage, use JSON.stringify before setting

localStorage.setItem("user", JSON.stringify(res.data));

to get the value from localStorage, use

JSON.parse(localStorage.getItem("user"))

Upvotes: 2

fawee
fawee

Reputation: 395

this.storage.set() returns a promise and resolves when key and value are set. (See Documentation)

So you need to call then like this:

this.storage.set('user', res.data).then(data => { 
    this.user.userdata = res.data;
    this.platform.exitApp();
}

Upvotes: 1

Related Questions