2021-08-30 14:35:20 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2022-06-10 16:33:15 +00:00
|
|
|
import { useDispatch, useSelect } from '@wordpress/data';
|
2021-08-30 14:35:20 +00:00
|
|
|
import { useCallback, useEffect, useRef } from '@wordpress/element';
|
|
|
|
import isShallowEqual from '@wordpress/is-shallow-equal';
|
2022-06-10 16:33:15 +00:00
|
|
|
import { CHECKOUT_STORE_KEY } from '@woocommerce/block-data';
|
2021-08-30 14:35:20 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
2022-06-10 16:33:15 +00:00
|
|
|
import type { CheckoutState } from '../../../data/checkout/types';
|
2021-08-30 14:35:20 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Custom hook for setting custom checkout data which is passed to the wc/store/checkout endpoint when processing orders.
|
|
|
|
*/
|
|
|
|
export const useCheckoutExtensionData = (): {
|
2022-06-10 16:33:15 +00:00
|
|
|
extensionData: CheckoutState[ 'extensionData' ];
|
2021-08-30 14:35:20 +00:00
|
|
|
setExtensionData: (
|
|
|
|
namespace: string,
|
|
|
|
key: string,
|
|
|
|
value: unknown
|
|
|
|
) => void;
|
|
|
|
} => {
|
2022-10-05 10:04:16 +00:00
|
|
|
const { __internalSetExtensionData } = useDispatch( CHECKOUT_STORE_KEY );
|
2022-06-10 16:33:15 +00:00
|
|
|
const { extensionData } = useSelect( ( select ) =>
|
|
|
|
select( CHECKOUT_STORE_KEY ).getCheckoutState()
|
|
|
|
);
|
2021-08-30 14:35:20 +00:00
|
|
|
const extensionDataRef = useRef( extensionData );
|
|
|
|
|
|
|
|
useEffect( () => {
|
|
|
|
if ( ! isShallowEqual( extensionData, extensionDataRef.current ) ) {
|
|
|
|
extensionDataRef.current = extensionData;
|
|
|
|
}
|
|
|
|
}, [ extensionData ] );
|
|
|
|
|
|
|
|
const setExtensionDataWithNamespace = useCallback(
|
|
|
|
( namespace, key, value ) => {
|
|
|
|
const currentData = extensionDataRef.current[ namespace ] || {};
|
2022-10-05 10:04:16 +00:00
|
|
|
__internalSetExtensionData( {
|
2021-08-30 14:35:20 +00:00
|
|
|
...extensionDataRef.current,
|
|
|
|
[ namespace ]: {
|
|
|
|
...currentData,
|
|
|
|
[ key ]: value,
|
|
|
|
},
|
|
|
|
} );
|
|
|
|
},
|
2022-10-05 10:04:16 +00:00
|
|
|
[ __internalSetExtensionData ]
|
2021-08-30 14:35:20 +00:00
|
|
|
);
|
|
|
|
|
|
|
|
return {
|
|
|
|
extensionData: extensionDataRef.current,
|
|
|
|
setExtensionData: setExtensionDataWithNamespace,
|
|
|
|
};
|
|
|
|
};
|