Last active
April 29, 2017 21:33
-
-
Save codeocelot/c403c3a79e7855504ee7586d6b2a6549 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import PropTypes from 'prop-types'; | |
const route = 'https://jsonplaceholder.typicode.com/posts'; | |
class AsyncPostHoC extends React.Component{ | |
constructor(props){ | |
super(props); | |
this.state = {}; | |
} | |
componentDidMount = () => { | |
makeRequest(this.props.postId); | |
} | |
makeRequest = () => { | |
const postId = this.props.postId; | |
fetch(`${route}/${postId}`) | |
.then((response) => response.json()) | |
.then((post) => this.setState({ post })); | |
} | |
render = () => { | |
const { children, postId, ...otherProps } = this.props; | |
// we want to render <ChildComponent {...this.props} post={this.state.post} /> | |
// We must never mutate another component, but we can clone the child and stuff any | |
// extra props we desire. | |
return React.cloneElement( | |
children, // children is actually a single react component, | |
{ | |
...otherProps, | |
post: this.state.post, | |
} | |
) | |
} | |
} | |
AsyncPostHoC.propTypes = { | |
postId: PropTypes.string.isRequired, | |
children: PropTypes.node.isRequired, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment