2024-10-07 10:42:56 +02:00
|
|
|
import { useState, useEffect } from '@wordpress/element';
|
|
|
|
import { log } from '../../../../ppcp-axo/resources/js/Helper/Debug';
|
|
|
|
|
2024-10-07 15:42:01 +02:00
|
|
|
/**
|
|
|
|
* Custom hook to load and manage the PayPal Commerce Gateway configuration.
|
|
|
|
*
|
|
|
|
* @param {Object} initialConfig - Initial configuration object.
|
|
|
|
* @return {Object} An object containing the loaded config and a boolean indicating if it's loaded.
|
|
|
|
*/
|
2024-10-07 10:42:56 +02:00
|
|
|
const usePayPalCommerceGateway = ( initialConfig ) => {
|
|
|
|
const [ isConfigLoaded, setIsConfigLoaded ] = useState( false );
|
|
|
|
const [ ppcpConfig, setPpcpConfig ] = useState( initialConfig );
|
|
|
|
|
|
|
|
useEffect( () => {
|
2024-10-07 15:42:01 +02:00
|
|
|
/**
|
|
|
|
* Function to load the PayPal Commerce Gateway configuration.
|
|
|
|
*/
|
2024-10-07 10:42:56 +02:00
|
|
|
const loadConfig = () => {
|
|
|
|
if ( typeof window.PayPalCommerceGateway !== 'undefined' ) {
|
|
|
|
setPpcpConfig( window.PayPalCommerceGateway );
|
|
|
|
setIsConfigLoaded( true );
|
|
|
|
} else {
|
|
|
|
log( 'PayPal Commerce Gateway config not loaded.', 'error' );
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-10-07 15:42:01 +02:00
|
|
|
// Check if the DOM is still loading
|
2024-10-07 10:42:56 +02:00
|
|
|
if ( document.readyState === 'loading' ) {
|
2024-10-07 15:42:01 +02:00
|
|
|
// If it's loading, add an event listener for when the DOM is fully loaded
|
2024-10-07 10:42:56 +02:00
|
|
|
document.addEventListener( 'DOMContentLoaded', loadConfig );
|
|
|
|
} else {
|
2024-10-07 15:42:01 +02:00
|
|
|
// If it's already loaded, call the loadConfig function immediately
|
2024-10-07 10:42:56 +02:00
|
|
|
loadConfig();
|
|
|
|
}
|
|
|
|
|
2024-10-07 15:42:01 +02:00
|
|
|
// Cleanup function to remove the event listener
|
2024-10-07 10:42:56 +02:00
|
|
|
return () => {
|
|
|
|
document.removeEventListener( 'DOMContentLoaded', loadConfig );
|
|
|
|
};
|
|
|
|
}, [] );
|
|
|
|
|
2024-10-07 15:42:01 +02:00
|
|
|
// Return the loaded configuration and the loading status
|
2024-10-07 10:42:56 +02:00
|
|
|
return { isConfigLoaded, ppcpConfig };
|
|
|
|
};
|
|
|
|
|
|
|
|
export default usePayPalCommerceGateway;
|