Update prefill-value on phone number change

This commit is contained in:
Philipp Stracker 2024-09-16 17:55:19 +02:00
parent 50daa3e99e
commit c8fd798f62
No known key found for this signature in database

View file

@ -32,6 +32,17 @@ const getSanitizedPhoneNumber = ( select ) => {
return billingPhone || shippingPhone || ''; 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. * Custom hook to synchronize the WooCommerce phone number with a React component state.
* *
@ -44,29 +55,25 @@ export const usePhoneSyncHandler = ( paymentComponent, setWooPhone ) => {
getSanitizedPhoneNumber( select ) getSanitizedPhoneNumber( select )
); );
// Initialize debounced setter for Fastlane. // Create a debounced function that updates the prefilled phone-number.
const debouncedSetWooPhoneRef = useRef(); const debouncedUpdatePhone = useRef(
debounce( ( number, component ) => {
if ( ! debouncedSetWooPhoneRef.current ) {
debouncedSetWooPhoneRef.current = debounce( ( number ) => {
setWooPhone( number ); 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( () => { useEffect( () => {
if ( phoneNumber ) { if ( paymentComponent && phoneNumber ) {
console.log( 'New phone number:', phoneNumber ); debouncedUpdatePhone( phoneNumber, paymentComponent );
debouncedSetWooPhoneRef.current( phoneNumber );
} }
}, [ phoneNumber ] ); }, [ debouncedUpdatePhone, paymentComponent, phoneNumber ] );
// Cleanup on unmount, canceling any pending debounced calls. // Cleanup on unmount, canceling any pending debounced calls.
useEffect( () => { useEffect( () => {
return () => { return () => {
if ( debouncedSetWooPhoneRef.current?.cancel ) { debouncedUpdatePhone.cancel();
debouncedSetWooPhoneRef.current.cancel();
}
}; };
}, [] ); }, [ debouncedUpdatePhone ] );
}; };