Search code examples
javascriptfirebasegoogle-cloud-firestoreredux-saga-firebase

Get collection reference in redux-saga-firebase


I'm unable to define a collection reference using redux-saga-firebase. I'm trying to define it like this:

const query = rsf.firestore.collection('players').where('up', '>', lastUpdated);

but I am getting

TypeError: _firebase_firebase__WEBPACK_IMPORTED_MODULE_6__.rsf.firestore.collection is not a function

I have tried also tried using .reference() as described here to no avail. I'm attempting to limit the number of documents synced from a collection per this suggestion. How can I get a collection reference for use in this function?

import { rsf } from '../../firebase/firebase';

export function* getPlayersFromDb() {
  const players = yield select(getPlayers);
  const lastUpdated = Math.max(...players.map(x => x.up));
  const query = rsf.firestore.collection('players').where('up', '>', lastUpdated);

yield fork(
  rsf.firestore.syncCollection,
  query,
  { successActionCreator: response => ({
            type: t.GET_PLAYERS_FROM_DB_SUCCESS,
            payload: [...response],
        }),
        failureActionCreator: () => ({
            type: t.GET_PLAYERS_FROM_DB_FAILURE,
            payload: [],
        }),
        transform: response => messageTransformer(response),
    }
);

}


Solution

  • The problem with your code is that you are mixing the official firestore SDK libraries with the redux-saga-firestore ones. If you want to get a collectionReference you have to do it using the official SDK, since the redux-saga-firestore libraries do not offer a method that returns that output.

    So, in order to get the collectionReference you would need to import the Firestore SDK and use almost the same code you already have on the getPlayersFromDb function, and it would look like this:

    const firebase = require("firebase");
    require("firebase/firestore");
    var db = firebase.firestore();
    
    ...
    
    export function* getPlayersFromDb() {
       ...
       const query = db.collection('players').where('up', '>', lastUpdated);
       ...
    }
    

    NOTE: As you can see on this redux-saga-firestore documentation, you could be using the getCollection method for that, but since you have a where clause, you would need to use a collectionReference to filter it anyway, so I am afraid there is no real solution for this with redux-saga-firestore.

    Hope this helps