Created
September 27, 2023 18:12
-
-
Save soker90/45869e59988ad4a18f70a35b457577c9 to your computer and use it in GitHub Desktop.
Await component
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
import type { JSX } from 'react'; | |
interface AwaitProps<T> { | |
promise: Promise<T>; | |
children: (result: T) => JSX.Element; | |
} | |
const Await = async <T,>({ promise, children }: AwaitProps<T>) => { | |
const result = await promise; | |
return children(result); | |
}; | |
export default Await; |
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
import { Await } from 'components'; | |
import { Suspense } from 'react'; | |
const Page = async () => { | |
// Page blocks on this data: | |
const data = await getData(); | |
return ( | |
<div> | |
<Suspense fallback='loading ...'> | |
{/* ...but renders a spinner for this slower data: */} | |
<Await promise={getOtherData(data)}> | |
{(stories) => ( | |
<ul> | |
{stories.map((story) => ( | |
<li key={story.id}>{story.title}</li> | |
))} | |
</ul> | |
)} | |
</Await> | |
</Suspense> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment