Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated cart ready event to return event instead of element #337

Merged
merged 2 commits into from
Oct 27, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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