Skip to content

Instantly share code, notes, and snippets.

@fsubal
Created July 20, 2026 23:00
Show Gist options
  • Select an option

  • Save fsubal/98977a5989ef165fde44ee2e4dbe5615 to your computer and use it in GitHub Desktop.

Select an option

Save fsubal/98977a5989ef165fde44ee2e4dbe5615 to your computer and use it in GitHub Desktop.
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