Created
April 19, 2018 06:07
-
-
Save christianchown/b995249d09d5b17d9827230294118d52 to your computer and use it in GitHub Desktop.
Synchronise a Firebase Database with a Redux Store
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
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