From ec963541198734626413b403a7bd42247a7a34c1 Mon Sep 17 00:00:00 2001 From: Trevor Date: Mon, 1 Feb 2021 10:44:18 -0800 Subject: [PATCH] useLayoutEffect for synchronous cleanup (#156) Fixes https://github.com/stripe/react-stripe-js/issues/154 on react17 --- .../createElementComponent.test.tsx | 27 +++++++++++++++++++ src/components/createElementComponent.tsx | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/components/createElementComponent.test.tsx b/src/components/createElementComponent.test.tsx index ba82573..e46c0ff 100644 --- a/src/components/createElementComponent.test.tsx +++ b/src/components/createElementComponent.test.tsx @@ -121,6 +121,33 @@ describe('createElementComponent', () => { false ); + + it('Can remove and add CardElement at the same time', () => { + let cardMounted = false; + mockElement.mount.mockImplementation(()=> { + if(cardMounted){ + throw new Error('Card already mounted'); + } + cardMounted = true; + }); + mockElement.destroy.mockImplementation(()=> { + cardMounted = false; + }); + + const {rerender} = render( + + + + ); + rerender( + + + + ); + + expect(mockElement.mount).toHaveBeenCalledTimes(2); + }); + it('gives the element component a proper displayName', () => { expect(CardElement.displayName).toBe('CardElement'); }); diff --git a/src/components/createElementComponent.tsx b/src/components/createElementComponent.tsx index 36a0ca2..dc2a8e4 100644 --- a/src/components/createElementComponent.tsx +++ b/src/components/createElementComponent.tsx @@ -114,7 +114,7 @@ const createElementComponent = ( } }, [options]); - React.useEffect(() => { + React.useLayoutEffect(() => { return () => { if (elementRef.current) { elementRef.current.destroy();