2021-03-16 11:40:22 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { doAction } from '@wordpress/hooks';
|
|
|
|
import { useCallback } from '@wordpress/element';
|
|
|
|
|
2021-03-31 14:22:27 +00:00
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { useStoreCart } from './cart/use-store-cart';
|
|
|
|
|
|
|
|
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 storeCart = useStoreCart();
|
|
|
|
|
|
|
|
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,
|
|
|
|
storeCart,
|
|
|
|
}
|
|
|
|
);
|
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-03-31 14:22:27 +00:00
|
|
|
[ storeCart ]
|
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
|
|
|
};
|