Last active
May 27, 2023 12:24
-
-
Save quisido/305d16d10094bf0b53bfdf9476b075f1 to your computer and use it in GitHub Desktop.
React Suspense with the Fetch API
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
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