|
| 1 | +import { Component } from "react"; |
| 2 | +import { useParams } from "react-router-dom"; |
| 3 | +import Carousel from "./Carousel"; |
| 4 | +import ErrorBoundary from "./ErrorBoundary"; |
| 5 | +import ThemeContext from "./ThemeContext"; |
| 6 | +import Modal from "./Modal"; |
| 7 | + |
| 8 | +class Details extends Component { |
| 9 | + state = { loading: true, showModal: false }; |
| 10 | + |
| 11 | + async componentDidMount() { |
| 12 | + const res = await fetch( |
| 13 | + `http://pets-v2.dev-apis.com/pets?id=${this.props.params.id}` |
| 14 | + ); |
| 15 | + const json = await res.json(); |
| 16 | + this.setState(Object.assign({ loading: false }, json.pets[0])); |
| 17 | + } |
| 18 | + toggleModal = () => this.setState({ showModal: !this.state.showModal }); |
| 19 | + adopt = () => (window.location = "http://bit.ly/pet-adopt"); |
| 20 | + render() { |
| 21 | + if (this.state.loading) { |
| 22 | + return <h2>loading … </h2>; |
| 23 | + } |
| 24 | + |
| 25 | + const { animal, breed, city, state, description, name, images, showModal } = |
| 26 | + this.state; |
| 27 | + |
| 28 | + return ( |
| 29 | + <div className="details"> |
| 30 | + <Carousel images={images} /> |
| 31 | + <div> |
| 32 | + <h1>{name}</h1> |
| 33 | + <h2>{`${animal} — ${breed} — ${city}, ${state}`}</h2> |
| 34 | + <ThemeContext.Consumer> |
| 35 | + {([theme]) => ( |
| 36 | + <button |
| 37 | + onClick={this.toggleModal} |
| 38 | + style={{ backgroundColor: theme }} |
| 39 | + > |
| 40 | + Adopt {name} |
| 41 | + </button> |
| 42 | + )} |
| 43 | + </ThemeContext.Consumer> |
| 44 | + <p>{description}</p> |
| 45 | + {showModal ? ( |
| 46 | + <Modal> |
| 47 | + <div> |
| 48 | + <h1>Would you like to adopt {name}?</h1> |
| 49 | + <div className="buttons"> |
| 50 | + <a href="https://bit.ly/pet-adopt">Yes</a> |
| 51 | + <button onClick={this.toggleModal}>No</button> |
| 52 | + </div> |
| 53 | + </div> |
| 54 | + </Modal> |
| 55 | + ) : null} |
| 56 | + </div> |
| 57 | + </div> |
| 58 | + ); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +const WrappedDetails = () => { |
| 63 | + const params = useParams(); |
| 64 | + return ( |
| 65 | + <ErrorBoundary> |
| 66 | + <Details params={params} /> |
| 67 | + </ErrorBoundary> |
| 68 | + ); |
| 69 | +}; |
| 70 | + |
| 71 | +export default WrappedDetails; |
0 commit comments