Skip to content

Instantly share code, notes, and snippets.

@christianchown
Created April 19, 2018 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianchown/b995249d09d5b17d9827230294118d52 to your computer and use it in GitHub Desktop.
Save christianchown/b995249d09d5b17d9827230294118d52 to your computer and use it in GitHub Desktop.
Synchronise a Firebase Database with a Redux Store
const syncedRetrievePromise = async (
ref,
dispatchValue,
dispatchKeyValue,
) => {
// retrieve and dispatch the current value of the ref
const data = await ref.once('value');
const val = data.val();
dispatchValue(val);
// set up listeners to dispatch changes, additions and deletions to children of the ref
const syncer = {};
const changed = ref.on('child_changed', (child) => {
if (child && child.key) {
const childVal = child.val();
if (JSON.stringify(val[child.key]) !== JSON.stringify(childVal)) { // to avoid unnecessary dispatches
dispatchKeyValue(child.key, childVal);
val[child.key] = childVal;
}
}
});
const added = ref.on('child_added', (child) => {
if (child && child.key) {
const childVal = child.val();
if (JSON.stringify(val[child.key]) !== JSON.stringify(childVal)) { // to avoid unnecessary dispatches
dispatchKeyValue(child.key, childVal);
val[child.key] = childVal;
}
}
});
const removed = ref.on('child_removed', (child) => {
if (child && child.key) {
dispatchKeyValue(child.key, null);
delete val[child.key];
}
});
// return an object that will remove the listeners
syncer.close = () => {
ref.off('child_changed', changed);
ref.off('child_added', added);
ref.off('child_removed', removed);
};
return syncer;
};
// Usage:
//
// const syncedWithStore = syncedRetrievePromise(
// ref, // firebase.database().ref(...);
// reduxDispatchValue, // dispatches ref's value to Redux
// reduxDispatchKeyValue // dispatches a sub key of ref to Redux
// );
//
// syncedWithStore.close(); // when done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment