Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support sync thenables for lazy() #14626

Merged
merged 2 commits into from Jan 18, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/react-reconciler/src/ReactFiberLazyComponent.js
Expand Up @@ -73,7 +73,10 @@ export function readLazyComponentType<T>(lazyComponent: LazyComponent<T>): T {
}
},
);
lazyComponent._result = thenable;
// Don't race with a sync thenable
if (lazyComponent._status === Pending) {
lazyComponent._result = thenable;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alt suggestion:

// Check if it resolved synchronously
if (lazyComponent._status === Resolved) {
  return lazyComponent._result;
}

Since if it's already resolved we don't need to throw the thenable

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Aaaah. That's why it had the loading state. Thanks.

}
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could also do the same for failure. But doesn't seem worth the extra code to me. Could be a recursive call but then there's more risk of messing it up and going into a stack overflow. Meh.

throw thenable;
}
}
Expand Down
17 changes: 17 additions & 0 deletions packages/react-reconciler/src/__tests__/ReactLazy-test.internal.js
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(['Loading...', 'Hi']);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
expect(ReactTestRenderer).toHaveYielded(['Loading...', 'Hi']);
expect(ReactTestRenderer).toHaveYielded(['Hi']);

expect(root).toMatchRenderedOutput('Hi');
});

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