···22 * @format
33 */
4455-import {AppRegistry} from 'react-native';
66-import App from './App';
55+import {AppRegistry} from 'react-native'
66+import App from './App'
7788-AppRegistry.registerComponent('App', () => App);
88+AppRegistry.registerComponent('App', () => App)
991010AppRegistry.runApplication('App', {
1111 rootTag: document.getElementById('root'),
1212-});
1212+})
+27
src/state/env.ts
···11+/**
22+ * The environment is a place where services and shared dependencies between
33+ * models live. They are made available to every model via dependency injection.
44+ */
55+66+import {getEnv, IStateTreeNode} from 'mobx-state-tree'
77+88+export class Environment {
99+ constructor() {}
1010+1111+ async setup() {}
1212+}
1313+1414+/**
1515+ * Extension to the MST models that adds the environment property.
1616+ * Usage:
1717+ *
1818+ * .extend(withEnvironment)
1919+ *
2020+ */
2121+export const withEnvironment = (self: IStateTreeNode) => ({
2222+ views: {
2323+ get environment() {
2424+ return getEnv<Environment>(self)
2525+ },
2626+ },
2727+})
+30
src/state/index.ts
···11+import {onSnapshot} from 'mobx-state-tree'
22+import {RootStoreModel, RootStore} from './models/root-store'
33+import {Environment} from './env'
44+import * as storage from './storage'
55+66+const ROOT_STATE_STORAGE_KEY = 'root'
77+88+export async function setupState() {
99+ let rootStore: RootStore
1010+ let data: any
1111+1212+ const env = new Environment()
1313+ try {
1414+ data = (await storage.load(ROOT_STATE_STORAGE_KEY)) || {}
1515+ rootStore = RootStoreModel.create(data, env)
1616+ } catch (e) {
1717+ console.error('Failed to load state from storage', e)
1818+ rootStore = RootStoreModel.create({}, env)
1919+ }
2020+2121+ // track changes & save to storage
2222+ onSnapshot(rootStore, snapshot =>
2323+ storage.save(ROOT_STATE_STORAGE_KEY, snapshot),
2424+ )
2525+2626+ return rootStore
2727+}
2828+2929+export {useStores, RootStoreModel, RootStoreProvider} from './models/root-store'
3030+export type {RootStore} from './models/root-store'
+16
src/state/models/root-store.ts
···11+/**
22+ * The root store is the base of all modeled state.
33+ */
44+55+import {Instance, SnapshotOut, types} from 'mobx-state-tree'
66+import {createContext, useContext} from 'react'
77+88+export const RootStoreModel = types.model('RootStore').props({})
99+1010+export interface RootStore extends Instance<typeof RootStoreModel> {}
1111+export interface RootStoreSnapshot extends SnapshotOut<typeof RootStoreModel> {}
1212+1313+// react context & hook utilities
1414+const RootStoreContext = createContext<RootStore>({} as RootStore)
1515+export const RootStoreProvider = RootStoreContext.Provider
1616+export const useStores = () => useContext(RootStoreContext)