Skip to content

Instantly share code, notes, and snippets.

@quisido
Last active May 27, 2023 12:24
Show Gist options
  • Save quisido/305d16d10094bf0b53bfdf9476b075f1 to your computer and use it in GitHub Desktop.
Save quisido/305d16d10094bf0b53bfdf9476b075f1 to your computer and use it in GitHub Desktop.
React Suspense with the Fetch API
class Suspense extends React.Component {
constructor(props) {
super(props);
this.state = {
promise: null
};
}
componentDidCatch(e) {
// Drake meme where he says no to errors here.
if (e instanceof Error) {
throw e;
}
// Drake meme where he says yes to promises here.
if (e instanceof Promise) {
this.setState({
promise: e
}, () => {
// When the promise finishes, go back to rendering the original children.
e.then(() => {
this.setState({ promise: null });
});
});
}
// This line isn't compatible with the Drake meme format.
else {
throw e;
}
}
render() {
if (this.state.promise) {
return this.props.fallback;
}
return this.props.children;
}
}
/*
<Suspense fallback={<Loading />}>
<PromiseThrower />
</Suspense>
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment