Storage Promise returns old (removed) data

I’ve come across a strange issue where data (in this case a jwt token) that has been removed from local storage is still being returned when calling get from ionic storage. As a result the jwt token is expired and therefore does not authenticate server-side.

The really strange thing is that it only occurs when I call getToken() from a particular function, but doesn’t occur anywhere else - in all other cases the new jwt token (stored with the same key) is returned and I’m getting the token from exactly the same place in both circumstances. An inspection in chrome also validates that there is only one token in local storage and is the most recent token. The previous token that is still being returned doesn’t exist in local storage at all.

//Saving the token to local storage
  saveToken(token) {
    this.storage.ready().then(()=> {
      this.storage.remove(this.TOKEN_KEY)
        .then(()=> {
          this.storage.set(this.TOKEN_KEY, token);
        });
    });
  };
//Retrieving the token from local storage
  getToken() {
      return this.storage.get(this.TOKEN_KEY);
  };
 //Remove the token key
  logout() {
    this.storage.remove(this.TOKEN_KEY);
  }

Is there some strange caching mechanism that I’m missing? Has anyone had a similar issue?

1 Like

Encountered same issue, still finding solution on this issue.

There is a race condition. You don’t have any idea when either remove or set has completed, and can very easily call getToken() before they have.

The simplest method for avoiding these problems is:

  • only read from storage once, at application startup (or initialization of whatever service provider is relevant)
  • only touch storage inside services, never from pages
  • only write to storage optimistically, with the intended audience being “the next time the app is started”
  • never use storage for in-app communication