Simple cache store

This commit is contained in:
Jori Lallo
2016-08-01 19:03:17 +03:00
parent 75fcf6383b
commit 9719496209
8 changed files with 115 additions and 36 deletions

View File

@ -0,0 +1,42 @@
import _ from 'lodash';
import { action, toJS } from 'mobx';
const CACHE_STORE = 'CACHE_STORE';
class CacheStore {
cache = {};
/* Computed */
get asJson() {
return JSON.stringify({
cache: this.cache,
});
}
/* Actions */
@action cacheWithId = (id, data) => {
this.cache[id] = toJS(data);
_.defer(() => localStorage.setItem(CACHE_STORE, this.asJson));
};
@action cacheList = (data) => {
data.forEach((item) => this.cacheWithId(item.id, item));
};
@action fetchFromCache = (id) => {
return this.cache[id];
}
constructor() {
// Rehydrate
const data = JSON.parse(localStorage.getItem(CACHE_STORE) || '{}');
this.cache = data.cache || {};
}
}
export default CacheStore;
export {
CACHE_STORE,
};