Skip to content

Instantly share code, notes, and snippets.

@seanchas116
Created September 21, 2017 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanchas116/708c7c725e330c8887572a2c7c2eb089 to your computer and use it in GitHub Desktop.
Save seanchas116/708c7c725e330c8887572a2c7c2eb089 to your computer and use it in GitHub Desktop.
Firebase value as custom MobX observable
import { Atom } from 'mobx'
import * as firebase from 'firebase'
// Custom observable for Firebase value
// see https://mobx.js.org/refguide/extending.html
export class FirebaseWatcher<T> {
private atom: Atom
private ref?: firebase.database.Reference
private _value: T
get value () {
if (this.atom.reportObserved()) {
return this._value
} else {
return this.defaultValue
}
}
constructor (public path: string, private defaultValue: T) {
this._value = defaultValue
this.atom = new Atom(
"FirebaseWatcher",
() => this.connect(),
() => this.disconnect()
)
}
private connect () {
this.ref = firebase.database().ref(this.path)
this.ref.on('value', snapshot => {
if (snapshot) {
this._value = snapshot.val()
this.atom.reportChanged()
}
})
}
private disconnect () {
if (this.ref) {
this.ref.off()
this.ref = undefined
}
}
}
const watcher = new FirebaseWatcher<Foo>('foo', defaultFoo)
autorun(() => {
console.log(watcher.value)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment