Jacobo Koenig
Jacobo Koenig

Reputation: 12514

Using React.js props on Redux's 'compose'

I am using react-redux-firebase and firestoreConnect to get information from my database and map it into props vía their premade reducer. To connect its information to my Component, I use the 'compose' method in the following way:

export default compose(
   connect(mapStateToProps, mapDispatchToProps),
   firestoreConnect([
      {
         collection: 'questions',
         doc: this.props.match.params.id,
         subcollection: 'messages',
      }
   ])
)(QuestionDetail);

As you can see, I am trying to access a specific document with an ID that was passed to the component as a prop from its parent. However, 'this' is undefined in the context of 'compose' and I therefore can't use it to access the props, and my parameter.

Is there any other way I can access the id passed to the component so I can request it to Firestore?

Upvotes: 1

Views: 1943

Answers (2)

Md Fazlul Karim
Md Fazlul Karim

Reputation: 353

It should work in older version of react-router.

But I assume you are using the latest version of React Router (v4+). So you have to wrap the whole component with the "withRouter" higher-order component. It will pass updated match, location, and history props to the wrapped component whenever it renders.

At first, you have to import the withRouter.

import { withRouter } from "react-router";

Then you have to wrap it with withRouter.

export default withRouter(compose(
   connect(mapStateToProps, mapDispatchToProps),
   firestoreConnect((props) => 
      [{
         collection: 'questions',
         doc: props.match.params.id,
         subcollections: [{ collection: 'messages' }],
      }]
      ))(QuestionDetail));

This works for me.

Upvotes: 1

Jacobo Koenig
Jacobo Koenig

Reputation: 12514

After a deeper search through the documentation I found that you can pass props to the firestoreConnect function (Note also that I was querying subcollections in the wrong way). The code ends up being:

export default compose(
   connect(mapStateToProps, mapDispatchToProps),
   firestoreConnect((props) => [
      {
         collection: 'questions',
         doc: props.match.params.id,
         subcollections: [{ collection: 'messages' }],
      }
   ])
)(QuestionDetail);

Upvotes: 1

Related Questions