Skip to content

Commit fa2a983

Browse files
authored
Return component from preload() (#15)
1 parent 106c326 commit fa2a983

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/__tests__/index.test.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ function getTestComponentModule() {
1515
return {
1616
isLoaded: () => loaded,
1717
loadCalls: () => loadCalls,
18+
OriginalComponent: TestComponent,
1819
TestComponent: async () => {
1920
loaded = true;
2021
loadCalls++;
@@ -138,4 +139,13 @@ describe("lazy", () => {
138139
await waitFor(() => expect(screen.queryByText("bar baz")).toBeTruthy());
139140
expect(ref?.current?.textContent).toBe("bar baz");
140141
});
142+
143+
it("returns the preloaded component when the preload promise resolves", async () => {
144+
const { TestComponent, OriginalComponent } = getTestComponentModule();
145+
const LazyTestComponent = lazy(TestComponent);
146+
147+
const preloadedComponent = await LazyTestComponent.preload()
148+
149+
expect(preloadedComponent).toBe(OriginalComponent);
150+
});
141151
});

src/index.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import { ComponentType, createElement, forwardRef, lazy } from "react";
22

33
export type PreloadableComponent<T extends ComponentType<any>> = T & {
4-
preload: () => Promise<void>;
4+
preload: () => Promise<T>;
55
};
66

77
export default function lazyWithPreload<T extends ComponentType<any>>(
88
factory: () => Promise<{ default: T }>
99
): PreloadableComponent<T> {
1010
const LazyComponent = lazy(factory);
11-
let factoryPromise: Promise<void> | undefined;
11+
let factoryPromise: Promise<T> | undefined;
1212
let LoadedComponent: T | undefined;
1313

1414
const Component = (forwardRef(function LazyWithPreload(props, ref) {
@@ -22,6 +22,7 @@ export default function lazyWithPreload<T extends ComponentType<any>>(
2222
if (!factoryPromise) {
2323
factoryPromise = factory().then((module) => {
2424
LoadedComponent = module.default;
25+
return LoadedComponent;
2526
});
2627
}
2728

0 commit comments

Comments
 (0)