Skip to content

Instantly share code, notes, and snippets.

@javivelasco
Created May 21, 2025 14:35
Show Gist options
  • Save javivelasco/9ac59952817cb4a2a16378bf1a63ebfd to your computer and use it in GitHub Desktop.
Save javivelasco/9ac59952817cb4a2a16378bf1a63ebfd to your computer and use it in GitHub Desktop.
Generator Component
import { Suspense, type ReactNode } from "react";
/**
* This function can be called with an AsyncGenerator Function that produces
* JSX. It will return a React Component that when rendered with some props
* will re-render with every value that the generator produces.
*/
export function generatorComponent<T>(
fn: (props: T) => AsyncGenerator<ReactNode, ReactNode, ReactNode>,
): React.FC<T> {
return function GeneratorComponentOutter(props: T) {
return <GeneratorComponent generator={fn(props)} />;
};
}
async function GeneratorComponent(props: {
generator: AsyncGenerator<ReactNode, ReactNode, ReactNode>;
}) {
const result = await props.generator.next();
if (result.done) {
return result.value;
}
return (
<Suspense fallback={result.value}>
<GeneratorComponent generator={props.generator} />
</Suspense>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment