Created
July 20, 2026 23:00
-
-
Save fsubal/98977a5989ef165fde44ee2e4dbe5615 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| import React, { Suspense } from "react"; | |
| interface Props { | |
| renderLoading?: () => React.ReactNode; | |
| renderError?: (error: Error) => React.ReactNode; | |
| children: React.ReactNode; | |
| } | |
| interface State { | |
| hasError: boolean; | |
| error: Error | null; | |
| } | |
| export class AsyncBoundary extends React.Component<Props, State> { | |
| readonly state: State = { | |
| hasError: false, | |
| error: null as Error | null, | |
| }; | |
| static getDerivedStateFromError(error: Error) { | |
| return { hasError: true, error }; | |
| } | |
| static readonly defaultProps = { | |
| renderLoading() { | |
| return <div>Loading...</div>; | |
| }, | |
| renderError(error: Error) { | |
| return ( | |
| <div> | |
| <h1>エラーが発生しました</h1> | |
| <p>{error.message}</p> | |
| </div> | |
| ); | |
| }, | |
| }; | |
| render() { | |
| return ( | |
| this.state.hasError ? ( | |
| this.props.renderError!(this.state.error!) | |
| ) : ( | |
| <Suspense fallback={this.props.renderLoading!()}> | |
| {this.props.children} | |
| </Suspense> | |
| ) | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment