Skip to content

Instantly share code, notes, and snippets.

@perfectbase
Last active April 27, 2025 14:24
Show Gist options
  • Save perfectbase/9b2a20f6bd78acefda13541cd4a15eb9 to your computer and use it in GitHub Desktop.
Save perfectbase/9b2a20f6bd78acefda13541cd4a15eb9 to your computer and use it in GitHub Desktop.
Await component for Next.js
import { Fragment, Suspense, type ReactNode } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
type AwaitProps<T> =
| {
promise: Promise<T>;
children: (data: T) => ReactNode;
fallback?: ReactNode;
errorComponent?: ReactNode | null;
}
| {
promise?: undefined;
children: ReactNode;
fallback?: ReactNode;
errorComponent?: ReactNode | null;
};
export function Await<T>({
promise,
children,
fallback = null,
errorComponent,
}: AwaitProps<T>) {
const MaybeErrorBoundary = errorComponent ? ErrorBoundary : Fragment;
return (
<MaybeErrorBoundary fallback={<>{errorComponent}</>}>
<Suspense fallback={<>{fallback}</>}>
{promise ? (
<AwaitResult promise={promise}>
{(data) => children(data)}
</AwaitResult>
) : (
<>{children}</>
)}
</Suspense>
</MaybeErrorBoundary>
);
}
type AwaitResultProps<T> = {
promise: Promise<T>;
children: (data: T) => ReactNode;
};
async function AwaitResult<T>({ promise, children }: AwaitResultProps<T>) {
const data = await promise;
return <>{children(data)}</>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment