Skip to content

Instantly share code, notes, and snippets.

@Yudhajitadhikary
Created January 10, 2021 15:02
Show Gist options
  • Save Yudhajitadhikary/b19bdb4743aafd65d8ecc240fb0e3bbb to your computer and use it in GitHub Desktop.
Save Yudhajitadhikary/b19bdb4743aafd65d8ecc240fb0e3bbb to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import axios from 'axios';
import {Stitch,RemoteMongoClient} from 'mongodb-stitch-browser-sdk';
// import Products from '../../components/Products/Products';
import BSON from 'bson';
import './Product.css';
class ProductPage extends Component {
state = { isLoading: true, product: null };
componentDidMount() {
const mongodb= Stitch.defaultAppClient.getServiceClient(RemoteMongoClient.factory,"mongodb-atlas");
mongodb.db('shop').collection('products')
.find({_id:new BSON.ObjectId(this.props.match.params.id)})
.asArray()
.then(productResponse=>{
const product=productResponse[0];
product._id=product._id.toString();
product.price=product.price.toString();
this.setState({isLoading:false,product:product})
})
.catch(err => {
this.setState({ isLoading: false });
console.log(err);
this.props.onError('Loading the product failed. Please try again later');
});
// axios
// .get('http://localhost:3100/products/' + this.props.match.params.id)
// .then(productResponse => {
// this.setState({ isLoading: false, product: productResponse.data });
// })
}
render() {
let content = <p>Is loading...</p>;
if (!this.state.isLoading && this.state.product) {
content = (
<main className="product-page">
<h1>{this.state.product.name}</h1>
<h2>{this.state.product.price}</h2>
<div
className="product-page__image"
style={{
backgroundImage: "url('" + this.state.product.image + "')"
}}
/>
<p>{this.state.product.description}</p>
</main>
);
}
if (!this.state.isLoading && !this.state.product) {
content = (
<main>
<p>Found no product. Try again later.</p>
</main>
);
}
return content;
}
}
export default ProductPage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment