Skip to content

Commit

Permalink
Support sync thenables for lazy() (facebook#14626)
Browse files Browse the repository at this point in the history
* Support sync thenables for lazy()

* Don't commit twice
  • Loading branch information
gaearon authored and n8schloss committed Jan 31, 2019
1 parent babeafb commit 561cdd0
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/react-reconciler/src/ReactFiberLazyComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export function readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
lazyComponent._status = Pending;
const ctor = lazyComponent._ctor;
const thenable = ctor();
lazyComponent._result = thenable;
thenable.then(
moduleObject => {
if (lazyComponent._status === Pending) {
Expand All @@ -73,7 +74,10 @@ export function readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
}
},
);
lazyComponent._result = thenable;
// Check if it resolved synchronously
if (lazyComponent._status === Resolved) {
return lazyComponent._result;
}
throw thenable;
}
}
Expand Down
17 changes: 17 additions & 0 deletions packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,23 @@ describe('ReactLazy', () => {
expect(root).toMatchRenderedOutput('Hi again');
});

it('can resolve synchronously without suspending', async () => {
const LazyText = lazy(() => ({
then(cb) {
cb({default: Text});
},
}));

const root = ReactTestRenderer.create(
<Suspense fallback={<Text text="Loading..." />}>
<LazyText text="Hi" />
</Suspense>,
);

expect(ReactTestRenderer).toHaveYielded(['Hi']);
expect(root).toMatchRenderedOutput('Hi');
});

it('multiple lazy components', async () => {
function Foo() {
return <Text text="Foo" />;
Expand Down

0 comments on commit 561cdd0

Please sign in to comment.