PayPalButtons callback function gets stale data

35 views Asked by At

I have the following code which is an Order component with a paypal button:

const Order = () => {
   const { order } = useOrderData();
   console.log("order (1):", order)

   const onPaypalCreateOrder = async (data, actions) => {
      console.log("order (2):", order)
      // ... 
   }

   return (
      <>
         <PayPalScriptProvider>
            <PayPalButtons
               createOrder={onPaypalCreateOrder}
            />
         </PayPalScriptProvider>
         <div>
         // (there's code here which allows me to update the order object asynchronously)
         </div>
      </>
   )
}

I stripped out irrelevant code to simplify things.

After the order component is loaded, I see:
order (1): (original value of order object)

When I do something that changes the order object, I will see:
order (1): (new value of order object)
So the useOrderData correctly provided the new order object to the Order component.

When I now click on the paypal button, I see:
order (1): (new value of order object)
order (2): (original value of order object)

So my order component does get the up-to-date values of the order object from the useOrderData hook, even after making changes. But for some reason, the PayPalButtons component is always working with stale data.

I tried to fix it by passing the order object to the onPaypalCreateOrder function when defining it in the PayPalButtons component:

const onPaypalCreateOrder = async (data, actions, order) => {
   console.log("order (2):", order)
   // ... 
}

<PayPalButtons
   createOrder={async (data, actions) => {
      console.log("order (3):", order)
      await onPaypalCreateOrder(data, actions, order)
   }}
/>

That didn't make any difference. Even here, I was getting:
order (1): (new value of order object)
order (2): (original value of order object)
order (3): (original value of order object)

I also tried wrapping the onPaypalCreateOrder in a useCallback:

const onPaypalCreateOrder = useCallback(async (data, actions) => {
      console.log("order (2):", order)
      // ... 
   }, [order])

That didn't make any difference either.

How can I get the up-to-date value of the order object in my onPaypalCreateOrder function?

0

There are 0 answers