Search code examples
reactjsfirebasereduxreact-reduxmapstatetoprops

TypeError: ownProps.match is Undefined


Unable to find a solution to the error TypeError: ownProps.match is undefined.

I am following a tutorial on react-redux and firebase to build a to-do app. The below code gives the component where I am redirected to when I click my Task/project on the home dashboard and get the data of that sepcific project in the projectDetails page from the firestore.

The ownProps in the mapStateToProps function is casuing the error mentioned.

Any help to solve this error or alternative way to implement this code will be appreciated.

import React from 'react'
import { connect } from 'react-redux'
import { firestoreConnect } from 'react-redux-firebase'
import { compose } from 'redux'

const ProjectDetails = (props) => {
  const { projects } = props;
  if (projects) {
    return (
      <div className="container section project-details">
        <div className="card z-depth-0">
          <div className="card-content">
            <span className="card-title">{projects.title}</span>
            <p>{projects.content}</p>
          </div>
          <div className="card-action grey lighten-4 grey-text">
            <div>Posted by {projects.authorFirstName} {projects.authorLastName}</div>
            <div>2nd September, 2am</div>
          </div>
        </div>
      </div>
    )
  } else {
    return (
      <div className="container center">
        <p>Loading project...</p>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  // console.log(state);
  const id = ownProps.match.params.id;
  const projects = state.firestore.data.projects;
  const project = projects ? projects[id] : null
  return {
    project: project
  }
}

export default compose(
  connect(mapStateToProps),
  firestoreConnect([{
    collection: 'projects'
  }])
)(ProjectDetails);

Facing issue in the above code here:

const mapStateToProps = (state, ownProps) => {
  // console.log(state);
  const id = ownProps.match.params.id;
  const projects = state.firestore.data.projects;
  const project = projects ? projects[id] : null
  return {
    project: project
  }
}

Solution

  • To pass the router configs to the mapStateToProps, you need to use the withRouter wrapper.

    Mentioned in the docs.

    This should work:

    const mapStateToProps = (state, ownProps) => {
      // console.log(state);
      const id = ownProps.match.params.id;
      const projects = state.firestore.data.projects;
      const project = projects ? projects[id] : null
      return {
        project: project
      }
    }
    
    export default compose(
      withRouter,
      connect(mapStateToProps),
      firestoreConnect([{
        collection: 'projects'
      }])
    )(ProjectDetails);