-
Notifications
You must be signed in to change notification settings - Fork 968
Expand file tree
/
Copy pathsetupRootStore.ts
More file actions
51 lines (44 loc) · 1.54 KB
/
setupRootStore.ts
File metadata and controls
51 lines (44 loc) · 1.54 KB
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 { RootStore, RootStoreSnapshot } from "../RootStore"
import * as storage from "app/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 | undefined
export async function setupRootStore(rootStore: RootStore) {
let restoredState: RootStoreSnapshot | undefined | null
try {
// load the last known state from AsyncStorage
restoredState = ((await storage.load(ROOT_STATE_STORAGE_KEY)) ?? {}) as RootStoreSnapshot
applySnapshot(rootStore, restoredState)
} catch (e) {
// if there's any problems loading, then inform the dev what happened
if (__DEV__) {
if (e instanceof Error) console.error(e.message)
}
}
// 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 }
}