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

Choose firestore subcollection when connecting component to redux with react-redux-firebase


I am using react-redux-firebase's fireStoreConnect() middleware with a screen in my react-native mobile app. At the time of connecting the component to the redux store, I want to specify the firestore sub-collection I connect to, which depends on the user that is navigating the app.

How should I specify the collection in firestoreConnect? The user id is in the redux store.

MWE:

import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { compose } from 'redux';
import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase';

class PhotosScreen extends Component {
  render() {
    return (
      <View>
        <Text> i plan the use this.props.images here </Text>
      </View>
    );
  }
}

const mapStateToProps = (state) => {

    // reference the subcollection of the user
    const images = state.firestore.data.images;

    return {
        images: images,
    }
}

export default compose(
    firestoreConnect([
        {
            collection: 'users',
            doc: "HOW DO I GET THE USERS ID HERE? IT IS IN REDUX STORE",
            subcollections: [{ collection: 'images' }]
        }
    ]),
    connect(mapStateToProps),
)(PhotosScreen)

Solution

  • In 1.x

    const enhance = compose(
      connect(
        (state) => ({
          someKey: state.someData
        })
      ),
      firebaseConnect(
        (props, firebaseInstance) => [
          { path: `${props.someKey}/someData` }
        ]
      )
    )
    

    In 2.x

    firebaseConnect(
      (props, store) => [
        { path: `${store.getState().someKey}/someData` }
      ]
    )
    

    Note how the 2nd argument in firebaseConnect changes from firebaseInstance to store from v1 to v2.

    This should get you what you need.