Skip to content

Commit

Permalink
Return cleanup function in useEffect
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardo committed May 6, 2021
1 parent c813036 commit 5b2980c
Showing 1 changed file with 24 additions and 30 deletions.
54 changes: 24 additions & 30 deletions client/payment-request/blocks/use-initialization.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit 5b2980c

Please sign in to comment.