-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
setupRootStore.ts
51 lines (44 loc) · 1.45 KB
/
setupRootStore.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* This file is where we do "rehydration" of your RootStore from AsyncStorage.
* This lets you persist your state between app launches.
*
* Navigation state persistence is handled in navigationUtilities.tsx.
*
* Note that Fast Refresh doesn't play well with this file, so if you edit this,
* do a full refresh of your app instead.
*
* @refresh reset
*/
import { applySnapshot, IDisposer, onSnapshot } from "mobx-state-tree"
import type { RootStore } from "../RootStore"
import * as storage from "../../utils/storage"
/**
* The key we'll be saving our state as within async storage.
*/
const ROOT_STATE_STORAGE_KEY = "root-v1"
/**
* Setup the root state.
*/
let _disposer: IDisposer
export async function setupRootStore(rootStore: RootStore) {
let restoredState: any
try {
// load the last known state from AsyncStorage
restoredState = (await storage.load(ROOT_STATE_STORAGE_KEY)) || {}
applySnapshot(rootStore, restoredState)
} catch (e) {
// if there's any problems loading, then inform the dev what happened
if (__DEV__) {
console.tron.error(e.message, null)
}
}
// stop tracking state changes if we've already setup
if (_disposer) _disposer()
// track changes & save to AsyncStorage
_disposer = onSnapshot(rootStore, (snapshot) => storage.save(ROOT_STATE_STORAGE_KEY, snapshot))
const unsubscribe = () => {
_disposer()
_disposer = undefined
}
return { rootStore, restoredState, unsubscribe }
}