Took some inspiration from https://github.com/pinqy520/mobx-persist to try this out
Usage:
import { types } from 'mobx-state-tree';
import moment from 'moment';
import { AsyncStorage } from 'react-native';
import { persist } from './persist';
const Store = types.model('Store', {
date: '1989-06-01',
hydrated: false,
get age() {
const birthday = moment(this.date);
return moment().diff(birthday, 'years');
},
}, {
setDate(date) {
this.date = date;
},
afterHydration() {
// This lifecycle is called after the store is hydrated
this.hydrated = true;
console.log('I feel refreshed!');
},
});
const store = Store.create();
persist('@MyStoreKey', store, {
storage: AsyncStorage, // AsyncStorage for React-Native, localStorage for web
jsonify: true, // Set to true if using AsyncStorage
}, {
date: true, // which keys to persist
});
export default store;
@ccfiel I used it in production and it mostly worked, but required one change, moving the
hydrated = true
statement to outside of theif (data)
block (otherwise hydrated will never be set to true because there is no data initially persisted).