2021-03-16 11:40:22 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { doAction } from '@wordpress/hooks';
|
2023-07-19 09:42:25 +00:00
|
|
|
import { select } from '@wordpress/data';
|
|
|
|
import { useCallback } from '@wordpress/element';
|
2021-03-31 14:22:27 +00:00
|
|
|
|
|
|
|
type StoreEvent = (
|
|
|
|
eventName: string,
|
|
|
|
eventParams?: Partial< Record< string, unknown > >
|
|
|
|
) => void;
|
|
|
|
|
2021-03-16 11:40:22 +00:00
|
|
|
/**
|
|
|
|
* Abstraction on top of @wordpress/hooks for dispatching events via doAction for 3rd parties to hook into.
|
|
|
|
*/
|
2021-03-31 14:22:27 +00:00
|
|
|
export const useStoreEvents = (): {
|
|
|
|
dispatchStoreEvent: StoreEvent;
|
|
|
|
dispatchCheckoutEvent: StoreEvent;
|
2021-03-16 11:40:22 +00:00
|
|
|
} => {
|
2021-03-31 14:22:27 +00:00
|
|
|
const dispatchStoreEvent = useCallback( ( eventName, eventParams = {} ) => {
|
|
|
|
try {
|
|
|
|
doAction(
|
|
|
|
`experimental__woocommerce_blocks-${ eventName }`,
|
|
|
|
eventParams
|
|
|
|
);
|
|
|
|
} catch ( e ) {
|
|
|
|
// We don't handle thrown errors but just console.log for troubleshooting.
|
2021-03-16 11:40:22 +00:00
|
|
|
// eslint-disable-next-line no-console
|
2021-03-31 14:22:27 +00:00
|
|
|
console.error( e );
|
|
|
|
}
|
|
|
|
}, [] );
|
2021-03-16 11:40:22 +00:00
|
|
|
|
2021-03-31 14:22:27 +00:00
|
|
|
const dispatchCheckoutEvent = useCallback(
|
|
|
|
( eventName, eventParams = {} ) => {
|
2021-03-16 11:40:22 +00:00
|
|
|
try {
|
2021-03-31 14:22:27 +00:00
|
|
|
doAction(
|
|
|
|
`experimental__woocommerce_blocks-checkout-${ eventName }`,
|
|
|
|
{
|
|
|
|
...eventParams,
|
2023-07-19 09:42:25 +00:00
|
|
|
storeCart: select( 'wc/store/cart' ).getCartData(),
|
2021-03-31 14:22:27 +00:00
|
|
|
}
|
|
|
|
);
|
2021-03-16 11:40:22 +00:00
|
|
|
} catch ( e ) {
|
|
|
|
// We don't handle thrown errors but just console.log for troubleshooting.
|
|
|
|
// eslint-disable-next-line no-console
|
|
|
|
console.error( e );
|
|
|
|
}
|
|
|
|
},
|
2021-06-16 12:44:40 +00:00
|
|
|
[]
|
2021-03-16 11:40:22 +00:00
|
|
|
);
|
|
|
|
|
2021-03-31 14:22:27 +00:00
|
|
|
return { dispatchStoreEvent, dispatchCheckoutEvent };
|
2021-03-16 11:40:22 +00:00
|
|
|
};
|