Search code examples
reactjsfirebasereact-reduxgoogle-cloud-firestorereact-redux-firebase

How to point firestoreConnect to a nested collection in React-Redux-Firebase?


The below line directs firestoreConnect to my collection labeled projects.

 { collection: 'projects' }

It works when the projects collection is immediately under the root like this:

root/
  projects/

But what if the projects collection is referenced by a doc which itself is within another collection, say, like this:

root/
  users/
    alice/
      projects/

How do I point firestoreConnect to the projects collection?

The documentation is silent on the matter.

Link to video
import React, { Component } from 'react'
import ProjectList from '../projects/ProjectList'
import Notifications from './Notifications'
import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'
import { Redirect } from 'react-router-dom'

class Dashboard extends Component {...}

const mapStateToProps = (state) => {
  // console.log(state);
  return {
    projects: state.firestore.ordered.projects,
    auth: state.firebase.auth,
  }
}

export default compose(
  connect(mapStateToProps),
  firestoreConnect([
    { collection: 'projects' }, // <-- Question is about this line
  ])
)(Dashboard)

Edit: Unsuccessful Attempt

From what I can piece together from the comments here it seems like the answer might be:

firestoreConnect([
  { 
    collection : 'users',
    doc        : 'alice',
    collection : 'projects',
  }
])

But that attempt has failed.


Solution

  • It can be done by passing multiple collection/doc settings to the subcollections parameter like so:

    firestoreConnect(() => [
      {
        collection: 'states',
        doc: 'CA',
        subcollections: [
          { collection: 'cities', doc: 'SF' },
          { collection: 'zips' }
        ]
      }
    ])
    

    This is noted in the firestoreConnect section of the react-redux-firebase docs (since it is a react specific HOC). The options that can be passed to queries are documented in the README of redux-firestore.

    If you are doing nested subcollections, you will probably want to use the v1.*.* versions since subcollections are stored along side top level collections in redux state. Note that the new version has a different API , as described in the v1.0.0 roadmap.

    Disclosure: I am the author of redux-firestore