Useful for headless stores using Javascript frameworks like React etc.
Initialising the script #
On a single page app, PreProduct’s script may not get reinitialised for each new product page. This causes an issue where the pre-order front-end doesn’t load. The below snippet solves this by listening to a custom event (we’ve used Gatsby‘s `onRouteUpdate` here).
window.addEventListener(`onRouteUpdate`, () => {
PPretry()
})
And from a React component:
React.useEffect(() => {
window.PPretry();
}, []);
And if you need to dynamically add/remove the script when a component is mounted/unmounted:
React.useEffect(() => {
const script = document.createElement(`script`);
script.src = `https://api.preproduct.io/preproduct-embed.js`;
script.async = true;
script.crossOrigin = 'anonymous';
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
};
}, []);
Keeping track of the currently selected variant #
If you use variants, you’ll also need to keep the variant= param in the page’s URL set to the currently selected variant. Listening for a change event on your variant field is a good way to go. Then running something similar to the below to populate the variant URL param.
let url = new URL(window.location.href);
url.searchParams.set("variant", variantId)
window.history.pushState(null, "", `${url.pathname}${url.search}`);
let locationChangeEvent = new Event('locationchange');
window.dispatchEvent(locationChangeEvent);
If your product pages use different buy-now button instances, you may need to tell PreProduct to re-evaluate the buttons on the page (that way it can smoothly hide and unhide them when needed).
This can be done by running the below:
window.PP_storedButtons = null;