woocommerce-paypal-payments/modules/ppcp-axo-block/resources/js/hooks/useFastlaneSdk.js

92 lines
2.6 KiB
JavaScript
Raw Normal View History

import { useEffect, useRef, useState, useMemo } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
2024-09-05 21:17:36 +02:00
import Fastlane from '../../../../ppcp-axo/resources/js/Connection/Fastlane';
import { log } from '../../../../ppcp-axo/resources/js/Helper/Debug';
import { useDeleteEmptyKeys } from './useDeleteEmptyKeys';
import useAllowedLocations from './useAllowedLocations';
import { STORE_NAME } from '../stores/axoStore';
2024-09-05 21:17:36 +02:00
/**
* Custom hook to initialize and manage the Fastlane SDK.
*
* @param {string} namespace - Namespace for the PayPal script.
* @param {Object} axoConfig - Configuration for AXO.
* @param {Object} ppcpConfig - Configuration for PPCP.
* @return {Object|null} The initialized Fastlane SDK instance or null.
*/
const useFastlaneSdk = ( namespace, axoConfig, ppcpConfig ) => {
2024-09-05 21:17:36 +02:00
const [ fastlaneSdk, setFastlaneSdk ] = useState( null );
const initializingRef = useRef( false );
const configRef = useRef( { axoConfig, ppcpConfig } );
const deleteEmptyKeys = useDeleteEmptyKeys();
const { isPayPalLoaded } = useSelect(
( select ) => ( {
isPayPalLoaded: select( STORE_NAME ).getIsPayPalLoaded(),
} ),
[]
);
const styleOptions = useMemo( () => {
return deleteEmptyKeys( configRef.current.axoConfig.style_options );
}, [ deleteEmptyKeys ] );
2024-09-05 21:17:36 +02:00
const allowedLocations = useAllowedLocations( axoConfig );
// Effect to initialize Fastlane SDK
2024-09-05 21:17:36 +02:00
useEffect( () => {
const initFastlane = async () => {
if ( initializingRef.current || fastlaneSdk || ! isPayPalLoaded ) {
2024-09-05 21:17:36 +02:00
return;
}
initializingRef.current = true;
log( 'Init Fastlane' );
2024-09-05 21:17:36 +02:00
try {
const fastlane = new Fastlane( namespace );
2024-09-05 21:17:36 +02:00
// Set sandbox environment if configured
if ( configRef.current.axoConfig.environment.is_sandbox ) {
window.localStorage.setItem( 'axoEnv', 'sandbox' );
}
2024-09-05 21:17:36 +02:00
// Connect to Fastlane with locale and style options
await fastlane.connect( {
locale: configRef.current.ppcpConfig.locale,
styles: styleOptions,
shippingAddressOptions: {
allowedLocations,
},
} );
2024-09-05 21:17:36 +02:00
// Set locale (hardcoded to 'en_us' for now)
fastlane.setLocale( 'en_us' );
2024-09-05 21:17:36 +02:00
setFastlaneSdk( fastlane );
} catch ( error ) {
log( `Failed to initialize Fastlane: ${ error }`, 'error' );
} finally {
initializingRef.current = false;
}
2024-09-05 21:17:36 +02:00
};
initFastlane();
}, [
fastlaneSdk,
styleOptions,
isPayPalLoaded,
namespace,
allowedLocations,
] );
// Effect to update the config ref when configs change
useEffect( () => {
configRef.current = { axoConfig, ppcpConfig };
}, [ axoConfig, ppcpConfig ] );
2024-09-05 21:17:36 +02:00
return fastlaneSdk;
};
export default useFastlaneSdk;