Created
January 24, 2023 09:16
-
-
Save Schniz/d52589cf608833af889d0e9eba83d2cf to your computer and use it in GitHub Desktop.
Generator component for Next.js 13
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
export function asyncComponent<T>( | |
fn: (props: T) => Promise<JSX.Element> | |
): React.FC<T> { | |
return fn as any; | |
} |
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 { Suspense } from "react"; | |
import { asyncComponent } from "./async-component"; | |
export function generatorComponent<T>( | |
fn: (props: T) => AsyncGenerator<JSX.Element, JSX.Element, JSX.Element> | |
): React.FC<T> { | |
return (props: T) => { | |
return <GeneratorComponent generator={fn(props)} />; | |
}; | |
} | |
const GeneratorComponent = asyncComponent( | |
async (props: { | |
generator: AsyncGenerator<JSX.Element, JSX.Element, JSX.Element>; | |
}) => { | |
const { generator } = props; | |
let result = await generator.next(); | |
if (result.done) { | |
return result.value; | |
} | |
return ( | |
<Suspense fallback={result.value}> | |
<GeneratorComponent generator={generator} /> | |
</Suspense> | |
); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment