Created
March 18, 2018 03:14
-
-
Save zevdg/ec0982e7ecd909534cf3576c3044b2c7 to your computer and use it in GitHub Desktop.
cache-first getter for firebase references
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
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); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. This is a nice wrapper.