Skip to content

Instantly share code, notes, and snippets.

@codeocelot
Last active April 29, 2017 21:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeocelot/c403c3a79e7855504ee7586d6b2a6549 to your computer and use it in GitHub Desktop.
Save codeocelot/c403c3a79e7855504ee7586d6b2a6549 to your computer and use it in GitHub Desktop.
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