Last active
November 13, 2020 03:27
-
-
Save dallen4/609960e4b0112a301b4bc835386d9bef to your computer and use it in GitHub Desktop.
BigCommerce EmbeddedCheckout component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react'; | |
import axios from 'axios'; | |
import { embedCheckout } from '@bigcommerce/checkout-sdk'; | |
import useCart from '@bigcommerce/storefront-data-hooks/cart/use-cart'; | |
import { nanoid } from 'nanoid'; | |
export default function EmbeddedCheckout(props: { containerId?: string }) { | |
const { data } = useCart(); | |
const [checkoutLoaded, setCheckoutLoaded] = React.useState(false); | |
const containerId = props.containerId || nanoid(); | |
React.useEffect(() => { | |
const handleEmbed = async () => { | |
const resp = await axios.post('/api/embedded-checkout', { cartId: data?.id }); | |
const url = resp.data.data.embedded_checkout_url; | |
try { | |
await embedCheckout({ | |
containerId, | |
url, | |
onError: (err) => console.error(err), | |
onFrameError: (err) => console.error(err), | |
}); | |
setCheckoutLoaded(true); | |
} catch (err) { | |
console.error(err); | |
} | |
}; | |
if (data && !checkoutLoaded) handleEmbed(); | |
}, [data]); | |
return <div id={containerId} />; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment