Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert Async Function to React Component
function asyncToReact(fn) {
class PromiseComponent extends React.Component {
state = { waiting: true, result: null };
componentDidMount() {
fn(...this.props.args).then(result => this.setState({ waiting: false, result }));
}
componentDidUpdate() {
fn(...this.props.args).then(result => this.setState({ waiting: false, result }));
}
shouldComponentUpdate(newProps) {
return this.props.args.some((arg, i) => !shallowEquals(arg, newProps.args[i]));
}
render() {
if (this.state.waiting) {
return null; // TODO: When Fiber works, use async dependency placeholder.
}
return this.props.mapper(this.props.data);
}
};
return function(...args) {
return {
then(mapper) {
return <PromiseComponent mapper={mapper} args={args} />;
}
};
}
}
fetch = asyncToReact(fetch);
@stereobooster

This comment has been minimized.

Copy link

stereobooster commented Jul 29, 2018

  • Do we need componentWillUnmount and "unsubscribe" for promise?
  • What about reject?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.