Skip to content

Commit

Permalink
Updated cart ready event to return event instead of element (#337)
Browse files Browse the repository at this point in the history
* updated cart ready event to return event instead of element

* add additional testing for change event
  • Loading branch information
martinalong-stripe authored Oct 27, 2022
1 parent d0a0e94 commit 3fc9c0f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 10 deletions.
20 changes: 15 additions & 5 deletions examples/hooks/10-Cart.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,23 @@ const ProductPage = ({options, productId}) => {
const cartElement = useCartElement();
const cartElementState = useCartElementState();

const handleCheckout = async () => {
const handleReady = (event) => {
console.log(event?.lineItems?.count);
};

const handleChange = (event) => {
console.log(event?.lineItems?.count);
};

const handleCheckout = (event) => {
console.log(event);
if (!cartElement) return;
// Redirect to Checkout page
// redirect to Checkout page would go here
cartElement.cancelCheckout('Error message here');
};

const handleLineItemClick = async (event) => {
if (!cartElement) return;
// Block native link redirect
const handleLineItemClick = (event) => {
// calling preventDefault blocks native link redirect
event.preventDefault();
console.log(event.url);
};
Expand All @@ -50,6 +58,8 @@ const ProductPage = ({options, productId}) => {
</button>
<CartElement
options={options}
onReady={handleReady}
onChange={handleChange}
onCheckout={handleCheckout}
onLineItemClick={handleLineItemClick}
/>
Expand Down
15 changes: 10 additions & 5 deletions src/components/createElementComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,19 @@ const createElementComponent = (
elementRef.current = element;
element.mount(domNode.current);
element.on('ready', (event) => {
if (type === 'cart' && setCartState) {
if (type === 'cart') {
// we know that elements.on event must be of type StripeCartPayloadEvent if type is 'cart'
// we need to cast because typescript is not able to infer which overloaded method is used based off param type
setCartState(
(event as unknown) as stripeJs.StripeCartElementPayloadEvent
);
if (setCartState) {
setCartState(
(event as unknown) as stripeJs.StripeCartElementPayloadEvent
);
}
// the cart ready event returns a CartStatePayload instead of the CartElement
callOnReady(event);
} else {
callOnReady(element);
}
callOnReady(element);
});

element.on('change', (event) => {
Expand Down

0 comments on commit 3fc9c0f

Please sign in to comment.