Skip to content

Instantly share code, notes, and snippets.

@soker90
Created September 27, 2023 18:12
Show Gist options
  • Save soker90/45869e59988ad4a18f70a35b457577c9 to your computer and use it in GitHub Desktop.
Save soker90/45869e59988ad4a18f70a35b457577c9 to your computer and use it in GitHub Desktop.
Await component
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;
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