From 5b2980c33074965c9da6b9f48535aeede1c5ab6a Mon Sep 17 00:00:00 2001 From: Ricardo Metring Date: Wed, 5 May 2021 22:25:22 -0300 Subject: [PATCH] Return cleanup function in useEffect --- .../blocks/use-initialization.js | 54 +++++++++---------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/client/payment-request/blocks/use-initialization.js b/client/payment-request/blocks/use-initialization.js index b12c85562cf..ae35e83f3f5 100644 --- a/client/payment-request/blocks/use-initialization.js +++ b/client/payment-request/blocks/use-initialization.js @@ -102,36 +102,30 @@ export const useInitialization = ( { // Whenever paymentRequest changes, hook in event listeners. useEffect( () => { - if ( paymentRequest ) { - // Remove all previously added event listeners first. - paymentRequest.removeAllListeners(); - - const cancelHandler = () => { - setIsFinished( false ); - setIsProcessing( false ); - setPaymentRequest( null ); - onClose(); - }; - - paymentRequest.on( 'shippingaddresschange', ( event ) => - shippingAddressChangeHandler( api, event ) - ); - - paymentRequest.on( 'shippingoptionchange', ( event ) => - shippingOptionChangeHandler( api, event ) - ); - - paymentRequest.on( 'paymentmethod', ( event ) => - paymentMethodHandler( - api, - completePayment, - abortPayment, - event - ) - ); - - paymentRequest.on( 'cancel', cancelHandler ); - } + const cancelHandler = () => { + setIsFinished( false ); + setIsProcessing( false ); + setPaymentRequest( null ); + onClose(); + }; + + paymentRequest?.on( 'shippingaddresschange', ( event ) => + shippingAddressChangeHandler( api, event ) + ); + + paymentRequest?.on( 'shippingoptionchange', ( event ) => + shippingOptionChangeHandler( api, event ) + ); + + paymentRequest?.on( 'paymentmethod', ( event ) => + paymentMethodHandler( api, completePayment, abortPayment, event ) + ); + + paymentRequest?.on( 'cancel', cancelHandler ); + + return () => { + paymentRequest?.removeAllListeners(); + }; }, [ paymentRequest ] ); return {