Skip to content

Instantly share code, notes, and snippets.

@Schniz
Created January 24, 2023 09:16
Show Gist options
  • Save Schniz/d52589cf608833af889d0e9eba83d2cf to your computer and use it in GitHub Desktop.
Save Schniz/d52589cf608833af889d0e9eba83d2cf to your computer and use it in GitHub Desktop.
Generator component for Next.js 13
export function asyncComponent<T>(
fn: (props: T) => Promise<JSX.Element>
): React.FC<T> {
return fn as any;
}
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