Last active
April 27, 2025 14:24
-
-
Save perfectbase/9b2a20f6bd78acefda13541cd4a15eb9 to your computer and use it in GitHub Desktop.
Await component for Next.js
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 { 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