Skip to content
This repository was archived by the owner on Feb 9, 2021. It is now read-only.

Persisting data locally

Darko Kukovec edited this page Jul 1, 2017 · 1 revision

Sometimes, you'll need to persist some data locally. Bellow is a basic example using localStorage, but the same concept can be applied to any type of persistance:

import {autorun} from 'mobx';
import {Store} from 'mobx-jsonapi-store';

class AppStore extends Store {
  constructor(data) {
    super(data);

    this.loadData(); // Load before init persist to avoid an unnecessary persisting cycle
    this.initPersistData();
  }

  loadData() {
    const data = localStorage.getItem('data'); // Load data from somewhere
    if (data) {
      this.insert(JSON.parse(data)); // Use insert to add it to the store
    }
  }

  initPersistData() {
    autorun(() => {
      const data = JSON.stringify(this.snapshot); // Use any logic you want (e.g. filter by type)
      localStorage.setItem('data', data);
    });
  }
}

The code will use MobX autorun to monitor the collection and persist the data only when something relevant changes (e.g. it will ignore changes to models you're not persisting).

Clone this wiki locally