Created
May 21, 2025 14:35
-
-
Save javivelasco/9ac59952817cb4a2a16378bf1a63ebfd to your computer and use it in GitHub Desktop.
Generator Component
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 { 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