{"size": 1817, "ext": "js", "max_stars_repo_path": "client/components/SingleProduct.js", "max_stars_repo_name": "reducks-team/grace-shopper", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "client/components/SingleProduct.js", "max_issues_repo_name": "reducks-team/grace-shopper", "max_issues_repo_issues_event_min_datetime": "2021-03-09T13:24:47.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T13:24:47.000Z", "max_forks_repo_path": "client/components/SingleProduct.js", "max_forks_repo_name": "reducks-team/grace-shopper", "max_forks_repo_forks_event_min_datetime": "2019-08-05T21:07:58.000Z", "max_forks_repo_forks_event_max_datetime": "2019-08-05T21:07:58.000Z"}
{"max_stars_count": null, "max_issues_count": 1, "max_forks_count": 1, "avg_line_length": 24.5540540541, "max_line_length": 74, "alphanum_fraction": 0.5844799119}
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {getProduct, addToCart} from '../store'

class SingleProduct extends Component {
  constructor(props) {
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  componentDidMount() {
    try {
      this.props.getProduct(this.props.match.params.productId)
    } catch (error) {
      console.trace(error)
    }
  }

  handleClick(userId, productId, price) {
    if (!userId) {
      alert('Please log in to add an item to the cart')
    } else {
      this.props.addToCart(userId, productId, price)
    }
  }

  render() {
    if (!this.props.singleProduct.id) {
      return <div />
    } else {
      return (
        <div>
          <img
            src={this.props.singleProduct.imageUrl}
            height={300}
            width={300}
          />
          <h1>{this.props.singleProduct.name}</h1>
          <p>{this.props.singleProduct.description}</p>
          <h2>${(this.props.singleProduct.price / 100).toFixed(2)}</h2>
          <button
            onClick={() =>
              this.handleClick(
                this.props.singleUser.id,
                this.props.match.params.productId,
                this.props.singleProduct.price
              )
            }
          >
            Add To Cart
          </button>
        </div>
      )
    }
  }
}

const mapStateToProps = state => {
  return {
    singleProduct: state.product.singleProduct,
    singleUser: state.user.singleUser
  }
}

const mapDispatchToProps = dispatch => {
  return {
    getProduct: productId => dispatch(getProduct(productId)),
    addToCart: (userId, productId, productCost) =>
      dispatch(addToCart(userId, productId, productCost))
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(SingleProduct)
