javascriptfirebasereact-reduxreact-redux-firebase

Show project detail using react-redux-firebase


enter image description here

I want to see the detail of my project but I cannot get the value to show. From console.log, I see that project is undefined. This means that the props do not bring any content.

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

const DetailProject = (props) => {
    // console.log(props)
    const { project } = props
    
    if (project) {
        return (
            <div className="container section project-details">
                <div className="card z-depth-0">
                    <div className="card-content">
                        <span className="card-title">{ project.title }</span>
                        <p>{ project.content }</p>
                    </div>
                    <div className="card-action gret lighten-4 grey-text">
                        <div>Post by { project.authorFirstname }</div>
                        <div>Create at { project.createAt }</div>
                    </div>
                </div>
            </div>
        )
    } else {
        return (
            <div className="container center">
                <p>Project loading...</p>
            </div>
        )
    }
}
   
const mapStateToProps = (state, ownProps) => {
    
    const id = ownProps.match.params.id;
    const projects = state.firestore.ordered.projects;
    const project = projects ? projects[id] : null;
    return {
        project: project
    }
}
export default compose(
    connect(mapStateToProps),
    firestoreConnect([
        { collection: 'projects' }
    ])
)(DetailProject);

Complete Code on CodeSandbox

The cards on the left are my projects. Clicking on one should show the details page for that project.

enter image description here


Solution

  • You are accessing the firestore data incorrectly in mapStateToProps.

    state.firestore.ordered.projects is an array of the projects in the correct order. You are using the id as the array index so you will not find a match.

    You can access a project by id, but you need to be looking in state.firestore.data.projects instead. This is the dictionary of projects keyed by id.

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

    This will get you the correct project in props.

    Now you have a new error to fix in the component. project.createAt is an object so you need to format it into a date string.