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 boxtoArray
: Turns a firebase ref to an observable ordered array of{key,value}
objectstoMap
: 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 :
Experiment with VanillaJS code
Experiment with React code
Read the docs
That's it folks !
Have any questions ?
Message me on @rakannimer or leave a comment here !
Top comments (1)
awesome read, iv'e encountered this issue myself so i decided to build a react firebase integration including auth, firestore, optional inline admin interface and it's open source. in fact i went ahead and made into a mini react cms solution.
check out orkan on github