Skip to content

Commit

Permalink
Checkout: Break cache of PayPal PPCP payment method button when cart …
Browse files Browse the repository at this point in the history
…changes or cancelling (#97253)

* Break cache of PayPalButtons when cancelling payment

* Break cache of PayPalButtons when cart changes
  • Loading branch information
sirbrillig authored Dec 9, 2024
1 parent e3aaaa6 commit d43bb39
Showing 1 changed file with 17 additions and 1 deletion.
18 changes: 17 additions & 1 deletion client/my-sites/checkout/src/payment-methods/paypal-js.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from '@paypal/react-paypal-js';
import debugFactory from 'debug';
import { useTranslate } from 'i18n-calypso';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import useCartKey from 'calypso/my-sites/checkout/use-cart-key';
import { PaymentMethodLogos } from '../components/payment-method-logos';

Expand Down Expand Up @@ -81,6 +81,9 @@ function PayPalSubmitButton( {
} ) {
const translate = useTranslate();
const togglePaymentMethod = useTogglePaymentMethod();
const [ forceReRender, setForceReRender ] = useState< number >( 0 );
const cartKey = useCartKey();
const { responseCart } = useShoppingCart( cartKey );

// Wait for PayPal.js to load before marking this payment method as active.
const [ { isResolved, isPending } ] = usePayPalScriptReducer();
Expand All @@ -90,6 +93,14 @@ function PayPalSubmitButton( {
}
}, [ isResolved, togglePaymentMethod ] );

useEffect( () => {
debug( 'cart changed; rerendering PayPalSubmitButton' );
// The PayPalButtons component appears to cache certain data about the
// order process and in order to make sure it has the latest data, we
// have to use the `forceReRender` prop.
setForceReRender( ( val ) => val + 1 );
}, [ responseCart ] );

// We have to wait for the active payment method to switch because the
// contents of the `onClick` function will change when the active state
// changes and if we render `PayPalButtons` too soon it will keep the old
Expand Down Expand Up @@ -139,6 +150,10 @@ function PayPalSubmitButton( {

const onCancel: PayPalButtonsComponentProps[ 'onCancel' ] = async () => {
debug( 'order cancelled' );
// The PayPalButtons component appears to cache certain data about the
// order process and in order to make sure it has the latest data, we
// have to use the `forceReRender` prop.
setForceReRender( ( val ) => val + 1 );
rejectPayPalApprovalPromise(
new Error( translate( 'The PayPal transaction was not approved.' ) )
);
Expand Down Expand Up @@ -176,6 +191,7 @@ function PayPalSubmitButton( {
// transaction system that the purchase is complete.
return (
<PayPalButtons
forceReRender={ [ forceReRender ] }
disabled={ disabled }
style={ { layout: 'horizontal' } }
fundingSource="paypal"
Expand Down

0 comments on commit d43bb39

Please sign in to comment.