Last active
March 31, 2023 15:57
-
-
Save sebmarkbage/c17122a302b912de9288b56d276b1dc9 to your computer and use it in GitHub Desktop.
Convert Async Function to React Component
This file contains 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
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} />; | |
} | |
}; | |
} | |
} |
This file contains 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
fetch = asyncToReact(fetch); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
componentWillUnmount
and "unsubscribe" for promise?reject
?