Last active
November 5, 2023 16:57
-
-
Save aight8/21d78a05ff0f648fb93671879b2c83aa to your computer and use it in GitHub Desktop.
react native / react-native-navigation / mobx / realm-js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createRalmApp() { | |
return new Realm.App({ | |
id: 'xxxxxx', | |
}) | |
} | |
function createRalm(user: Realm.User | null) { | |
const realmConfig = { | |
schema: [ | |
// your schemas.. | |
], | |
deleteRealmIfMigrationNeeded: true, | |
} as Realm.Configuration | |
// if (user) { | |
// realmConfig.sync = { | |
// flexible: true, | |
// user: user, | |
// } | |
// } | |
return new Realm(realmConfig) | |
} | |
class AppState { | |
app: Realm.App = createRalmApp() | |
user: Realm.User | null = this.app.currentUser | |
realm: Realm = createRalm(this.user) | |
constructor() { | |
makeAutoObservable(this, { | |
app: observable.ref, | |
user: observable.ref, | |
realm: observable.ref, | |
}) | |
devDebugMobxEvents() | |
} | |
// write back the app user the user property to trigger a rerender | |
updateUser() { | |
this.user = this.app.currentUser | |
} | |
} | |
export const State = new AppState() | |
Navigation | |
.events() | |
.registerAppLaunchedListener(() => { | |
// a function which sets the default options | |
defaults() | |
// runs initially | |
// re-render when the user property changes | |
autorun(() => { | |
if (!State.user) { | |
// calls Navigation.setRoot for the login layout | |
Layout.setLoginRoot() | |
} else { | |
// calls Navigation.setRoot for the user layout | |
Layout.setUserRoot() | |
} | |
}, { | |
name: 'Set Navigation Layout on User Change', | |
}) | |
}) | |
// runs initially | |
// re-renders when the app reports a change (especially user login/logout/switch) | |
autorun(() => { | |
State.app.addListener(() => { | |
State.updateUser() | |
}) | |
}, { | |
name: '[State.app] notification -> update State.user', | |
}) | |
// runs initially | |
// re-renders when the user reports a change (something of the user changed so it must be invalidated) | |
autorun(() => { | |
State.user?.addListener(() => { | |
State.updateUser() | |
}) | |
}, { | |
name: '[State.user] notification -> update State.user', | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment