Skip to content Skip to sidebar Skip to footer

Firebase Return Onsnapshot Promise

I'm using firebase/firestore and I'm looking a way to return promise of snapshot. onlineUsers(){ // i want to return onSnapshot return this.status_database_ref.where('stat

Solution 1:

A Promise in JavaScript can resolve (or reject) exactly once. A onSnapshot on the other hand can give results multiple times. That's why onSnapshot doesn't return a promise.

In your current code, you're left with a dangling listener to status_database_ref. Since you don't do anything with the data, it is wasteful to keep listening for it.

Instead of using onSnapshot, use get:

onlineUsers(callback){
    this.status_database_ref.where('state','==','online').get((querySnapshot)=>{
        callback(querySnapshot.size)
    }) 
}

Or in your original approach:

onlineUsers(){
    returnthis.status_database_ref.where('state','==','online').get();
}

Solution 2:

I know it's too late but here is my solution using TypeScript & Javascript.

TYPESCRIPT

const _db=firebase.firestore;
const _collectionName="users";

    onDocumentChange = (document: string,
    callbackSuccess: (currentData: firebase.firestore.DocumentData, source?: string | 'Local' | 'Server') => void,
    callbackError?: (e: Error) => void,
    callbackCompletion?: () => void) => {
    this._db.collection(this._collectionName).doc(document).onSnapshot(
        {
            // Listen for document metadata changesincludeMetadataChanges: true
        },
        (doc) => {
            const source = doc.metadata.hasPendingWrites ? 'Local' : 'Server';
            callbackSuccess(doc.data(), source);
        },
        (error) =>callbackError(error),
        () =>callbackCompletion()
    );
};

JAVASCRIPT (ES5)

var _this = this;
onDocumentChange = function (document, callbackSuccess, callbackError, callbackCompletion) {
    _this._db.collection(_this._collectionName).doc(document).onSnapshot({
        // Listen for document metadata changesincludeMetadataChanges: true
    }, function (doc) {
        var source = doc.metadata.hasPendingWrites ? 'Local' : 'Server';
        callbackSuccess(doc.data(), source);
    }, function (error) { returncallbackError(error); }, function () { returncallbackCompletion(); });
};

Solution 3:

I found a way to do that

onlineUsers(callback){
   returnthis.status_database_ref.where('state','==','online').onSnapshot((querySnapshot)=>{
        callback(querySnapshot.size)
    }) 
}

componentDidMount(){

    this.unsubscribe = firebaseService.onlineUsers(this.onUpdateOnlineUsers);
    console.log(this.unsubscribe)
}
onUpdateOnlineUsers(count){
    this.setState({count})
}
componentWillUnmount(){
    this.unsubscribe();

}

Post a Comment for "Firebase Return Onsnapshot Promise"