We’re trying to integrate Tolstoy Shoppable Videos onto our Headless Shopify Hydrogen site. I have a component to handle this, however, the add-to-cart is not working so I need to build the custom logic.
From my understanding, and testing, it doesn’t look like I can use the standard fetch('/cart/add.js')
and would need to utilise the CartProvider
and <AddToCartButton>
then use state and useEffect to trigger the addToCart once I receive the variantId from Tolstoy.
The variantId is coming back from Tolstoy in the payload just fine, it’s passing that to the AddToCart and triggering the event that I think I’m struggling with.
I have tried quite a few variations of this logic but I’m getting nowhere.
import { CartProvider } from '~/provider/cart'
import { AddToCartButton } from '~/components'
import { SectionTolstoyModuleProps } from './TolstoyModule.types'
import React, { useEffect, useState } from 'react'
interface AddToCartHandlerProps {
variantId: string
quantity: number
onAddToCartSuccess: (payload: any) => void
}
const AddToCartHandler: React.FC<AddToCartHandlerProps> = ({ variantId, quantity, onAddToCartSuccess }) => {
const [isAdding, setIsAdding] = useState(false)
useEffect(() => {
const handleTolstoyEvent = (event: MessageEvent) => {
if (event.data && event.data.eventName === 'tolstoy_add_to_cart') {
setIsAdding(true)
}
}
window.addEventListener('message', handleTolstoyEvent)
return () => {
window.removeEventListener('message', handleTolstoyEvent)
}
}, [])
return (
<CartProvider>
{isAdding && (
<AddToCartButton
lines={[
{
quantity: 1,
merchandiseId: variantId,
},
]}
variantId={variantId}
quantity={quantity}
onSubmit={() => {
console.log('ON SUBMIT FIRED')
setIsAdding(false)
onAddToCartSuccess({ variantId })
}}
/>
)}
</CartProvider>
)
}
export const TolstoyModule: React.FC<SectionTolstoyModuleProps> = ({
tags = [],
publishId,
productId,
tolstoyType,
}) => {
const tagsString = tags?.join(',')
const handleAddToCartSuccess = (payload: any) => {
window.tolstoyWidget.postMessage({
...payload,
eventName: 'tolstoy_add_to_cart_success',
})
}
return (
<div
data-tags={tagsString}
className={`tolstoy-${tolstoyType}`}
data-publish-id={publishId}
data-product-id={productId}>
<AddToCartHandler variantId={productId} quantity={1} onAddToCartSuccess={handleAddToCartSuccess} />
</div>
)
}
Any help is much appreciated.