Tame your Firebase Realtime Database with MobX
source link: https://www.tuicool.com/articles/hit/rENV7zQ
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
While Firebase's Realtime Database enables you to build almost anything, manipulating realtime data in your app can lead to writing code that is hard to debug, understand and maintain.
Enter MobX and mobx-firebase-database .
MobX is a powerful state management library that works with all front-end frameworks.
MobX-firebase-database allows you to map your Firebase realtime data to MobX observables (box, array or map) with firebase
, firebase-admin
or react-native-firebase
Using it
mobx-firebase-database
exports one function getMobxFire, call it with firebase and your firebase config to get access to your toolbox.
import getMobxFire from "mobx-firebase-database"; import firebase from "firebase/app"; import "firebase/database"; // Don't worry about calling it more than once. const { toBox, toArray, toMap, getFirebaseRef, destroy } = getMobxFire({ config, firebase });
-
toBox
: Turns a firebase ref to an observable box -
toArray
: Turns a firebase ref to an observable ordered array of{key,value}
objects -
toMap
: Turns a firebase ref (with any query you can think of) to an observable map:Map<K,V>
where K is the child key name and V is the child value
Now that we have access to this set of primitives to build on. We can easily use them to build UIs.
Using mobx-firebase-database
with Vanilla JS
import { observe } from "mobx"; import getMobxFirebase from "mobx-firebase-database"; import firebase from "firebase/app"; import "firebase/database"; import { config } from "../config"; const PATH = `TEST_SANDBOX/posts/1`; let counter = 0; const pretty = obj => `<pre>${JSON.stringify(obj, null, 2)}</pre>`; const { toBox } = getMobxFirebase({ config, firebase }); const refToPost = firebase.database().ref(PATH); const { value } = toBox(refToPost); setInterval(() => { counter += 1; // Write data fo firebase here refToPost.set({ title: `post title ${counter}` }); }, 500); observe(value, () => { // see it update here document.getElementById("root").innerHTML = pretty( value.get() ); });
Using mobx-firebase-database
with ReactJS
const App = observer(() => { // Render it here return <pre>{JSON.stringify(value.get())}</pre>; }); render(<App />, document.getElementById("root"));
It's that simple :)
Want to know more :
That's it folks !
Have any questions ?
Message me on @rakannimer or leave a comment here !
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK