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

Prevent Embedded Checkout unmount errors #446

Merged
merged 1 commit into from
Sep 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions src/components/EmbeddedCheckout.client.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,29 @@ describe('EmbeddedCheckout on the client', () => {
);
expect(mockEmbeddedCheckout.unmount).toBeCalled();
});

it('does not throw when the Embedded Checkout instance is already destroyed when unmounting', async () => {
const {container, rerender} = render(
<EmbeddedCheckoutProvider stripe={mockStripe} options={fakeOptions}>
<EmbeddedCheckout />
</EmbeddedCheckoutProvider>
);

await act(() => mockEmbeddedCheckoutPromise);

expect(mockEmbeddedCheckout.mount).toBeCalledWith(container.firstChild);

mockEmbeddedCheckout.unmount.mockImplementation(() => {
throw new Error('instance has been destroyed');
});

expect(() => {
rerender(
<EmbeddedCheckoutProvider
stripe={mockStripe}
options={fakeOptions}
></EmbeddedCheckoutProvider>
);
}).not.toThrow();
});
});
13 changes: 11 additions & 2 deletions src/components/EmbeddedCheckout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,17 @@ const EmbeddedCheckoutClientElement = ({
// Clean up on unmount
return () => {
if (isMounted.current && embeddedCheckout) {
embeddedCheckout.unmount();
isMounted.current = false;
try {
embeddedCheckout.unmount();
isMounted.current = false;
} catch (e) {
// Do nothing.
// Parent effects are destroyed before child effects, so
// in cases where both the EmbeddedCheckoutProvider and
// the EmbeddedCheckout component are removed at the same
// time, the embeddedCheckout instance will be destroyed,
// which causes an error when calling unmount.
}
}
};
}, [embeddedCheckout]);
Expand Down
Loading