Skip to content

Instantly share code, notes, and snippets.

@zevdg
Created March 18, 2018 03:14
Show Gist options
  • Save zevdg/ec0982e7ecd909534cf3576c3044b2c7 to your computer and use it in GitHub Desktop.
Save zevdg/ec0982e7ecd909534cf3576c3044b2c7 to your computer and use it in GitHub Desktop.
cache-first getter for firebase references
function cacheFirstGet(ref, handlerFunc, timeout = 10000) {
let options = {};
if (ref instanceof firebase.firestore.DocumentReference) {
options.includeMetadataChanges = true;
} else if (ref instanceof firebase.firestore.Query) {
options.includeQueryMetadataChanges = true;
} else {
throw new Error("Input must implement DocumentReference or Query");
}
let cacheIsLoaded = false;
let unsubscribe = ref.onSnapshot(options, function(snapshot) {
if (!snapshot.metadata.fromCache) {
// when we recieve a response from the network we can stop listening
unsubscribe();
handlerFunc(snapshot);
return;
}
if (!cacheIsLoaded) {
cacheIsLoaded = true;
handlerFunc(snapshot);
}
});
// handles unsubscribing when the network never responds
window.setTimeout(unsubscribe, timeout);
};
@rheinardkorf
Copy link

Thanks. This is a nice wrapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment