Ionic Storage not updated if not reloaded?


#1

I’m updating using:
this.storage.set('member', JSON.stringify(data));

But I have to reload the app if I want to see the new value in my other tabs.

Why is that? Can it be fixed?


#2

how do you retrieve datas ?


#3

Like this:

export class ProfilePage {
    member: any = {};

    constructor(public navCtrl: NavController, private storage: Storage) {

    }

    ionViewDidLoad() {
        this.storage.get('member').then(member => {
            this.member = JSON.parse(member);
        });
    }
}

#4

hmm I don’t know seems good try to add () :

        this.storage.get('member').then((member) => {
            this.member = JSON.parse(member);
        });

#5

Still not working…

Anyway, I’ll use window.location.reload(); to reload the app when the user saves his preferences.


#6

This is an incredibly wasteful idea.

What I would do instead is to isolate all interaction with storage into a provider that looks something like this:

export interface Preferences {
  // stuff goes here
}

export class PreferenceService {
  private _prefs = new BehaviorSubject<Preferences | undefined>(undefined);

  constructor(private _storage: Storage) {
    this._storage.ready().then(() => {
      this._storage.get('prefs').then((prefs) => {
        this._prefs.next(prefs);
      });
    });
  }

  getPreferences(): Observable<Preferences | undefined> {
    return this._prefs.asObservable();
  }

  setPreferences(prefs: Preferences): void {
    this._prefs.next(prefs);
    this._storage.set('prefs', prefs);
  }
}

Each page that cares about the preferences can inject this provider and be seamlessly updated when the preferences change. The write is optimistic, which values performance over transactional integrity. I think that’s a good choice here because there isn’t anything we can reasonably do in the case that the storage write hasn’t completed in time.