mirror of
https://github.com/woocommerce/woocommerce-paypal-payments.git
synced 2025-09-05 08:59:14 +08:00
✨ Update prefill-value on phone number change
This commit is contained in:
parent
50daa3e99e
commit
c8fd798f62
1 changed files with 23 additions and 16 deletions
|
@ -32,6 +32,17 @@ const getSanitizedPhoneNumber = ( select ) => {
|
|||
return billingPhone || shippingPhone || '';
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates the prefilled phone number in the Fastlane CardField component.
|
||||
*
|
||||
* @param {Object} paymentComponent - The CardField component from Fastlane
|
||||
* @param {string} phoneNumber - The new phone number to prefill.
|
||||
*/
|
||||
const updatePrefills = ( paymentComponent, phoneNumber ) => {
|
||||
console.log( 'Update the phone prefill value', phoneNumber );
|
||||
paymentComponent.updatePrefills( { phoneNumber } );
|
||||
};
|
||||
|
||||
/**
|
||||
* Custom hook to synchronize the WooCommerce phone number with a React component state.
|
||||
*
|
||||
|
@ -44,29 +55,25 @@ export const usePhoneSyncHandler = ( paymentComponent, setWooPhone ) => {
|
|||
getSanitizedPhoneNumber( select )
|
||||
);
|
||||
|
||||
// Initialize debounced setter for Fastlane.
|
||||
const debouncedSetWooPhoneRef = useRef();
|
||||
|
||||
if ( ! debouncedSetWooPhoneRef.current ) {
|
||||
debouncedSetWooPhoneRef.current = debounce( ( number ) => {
|
||||
// Create a debounced function that updates the prefilled phone-number.
|
||||
const debouncedUpdatePhone = useRef(
|
||||
debounce( ( number, component ) => {
|
||||
setWooPhone( number );
|
||||
}, PHONE_DEBOUNCE_DELAY );
|
||||
}
|
||||
updatePrefills( component, number );
|
||||
}, PHONE_DEBOUNCE_DELAY )
|
||||
).current;
|
||||
|
||||
// Invoke debounced setter when phone number changes.
|
||||
// Invoke debounced function when paymentComponent or phoneNumber changes.
|
||||
useEffect( () => {
|
||||
if ( phoneNumber ) {
|
||||
console.log( 'New phone number:', phoneNumber );
|
||||
debouncedSetWooPhoneRef.current( phoneNumber );
|
||||
if ( paymentComponent && phoneNumber ) {
|
||||
debouncedUpdatePhone( phoneNumber, paymentComponent );
|
||||
}
|
||||
}, [ phoneNumber ] );
|
||||
}, [ debouncedUpdatePhone, paymentComponent, phoneNumber ] );
|
||||
|
||||
// Cleanup on unmount, canceling any pending debounced calls.
|
||||
useEffect( () => {
|
||||
return () => {
|
||||
if ( debouncedSetWooPhoneRef.current?.cancel ) {
|
||||
debouncedSetWooPhoneRef.current.cancel();
|
||||
}
|
||||
debouncedUpdatePhone.cancel();
|
||||
};
|
||||
}, [] );
|
||||
}, [ debouncedUpdatePhone ] );
|
||||
};
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue