javascriptreactjsjbuilderreact-class-based-component

How do i put entities into props after fetching it from componetDidMount?


inside componentDidMount Im calling the dispatched fetchReviews. but once mounted how does the fetched reviews get set in props?

business show component:

import React from "react";
import { Link } from 'react-router-dom';
import Star from "../star/star";

class BusinessShowIndex extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            loading: true
        }
    }

    componentDidMount() {
        this.props.fetchReviews(this.props.business.id)
        // .then (() => this.setState({reviews: this.props.reviews}))
        this.setState({loading: false})
        console.log(this.props)
    }
    render() {
        const { business, reviews } = this.props;
        if (!this.props.reviews) return null;
        if (this.state.loading === true) {
            return <p>Loading...</p>
        }
        return (
            <div className="business-show">
                <Link to={`/business/${business.id}`} className='link-business-index'>
                    <img className="business-index-photo" src={business.photo_urls[0]} alt=""/>
                    <p className="business-index-name">{business.name}</p>
                    <Star reviews={reviews}/>
                    <p className="business-index-city">{business.city}</p>
                    <p className="business-index-cost">Cost: {business.cost}</p>
                    <p className="business-index-hours">Hours: {business.open} - {business.close}</p>
                </Link>
            </div>
        )
    }
};

export default BusinessShowIndex;

container:

import { connect } from 'react-redux';
import {fetchReviews} from '../../actions/review_actions';
import { withRouter } from 'react-router-dom';
import BusinessShowIndex from './business_show_index';

const mapStateToProps = (state, ownProps) => ({
    business: state.entities.businesses[ownProps.business.id],
    currentUser: state.entities.users[state.session.id],
    reviews: Object.values(state.entities.reviews)
})
const mapDispatchToProps = dispatch => ({
    fetchReviews: (businessId) => dispatch(fetchReviews(businessId))
})

export default withRouter(connect(mapStateToProps, mapDispatchToProps)(BusinessShowIndex));

let me know what else you need to see! thank you! also any advice to clean code? taking any suggestions.

Inside componentDidMount Im calling the dispatched fetchReviews. but once mounted how does the fetched reviews get set in props?


Solution

  • You can get using this.props.review

    Check your mapStateToProps function. You get the entire state there and it returns whatsever part of it you want to return.