Loading the Subscription Manager inside a Single-Page App

Prevent stale data and re-firing notifications when navigating in React and other SPAs

View as Markdown

The Ordergroove Subscription Manager (SM) uses a singleton data store. When loading the SM inside a single-page app (e.g. built with React), you may notice odd behavior when navigating away from and back to the SM. For example, the order data may be stale, or previous toast notifications may re-fire. This is because the SM data store only reinitializes when the page does a full reload, not on client-side navigations. When you navigate back to the page it uses the same data as the initial load.

To reinitialize the SM data store without a full page reload and prevent issues with stale data, call window.og.smi.reset() whenever you navigate back to the page that loads the SM.

For example, this is what that could look like in a React component:

1import { useState, useEffect } from "react";
2
3const MERCHANT_ID = "YOUR_MERCHANT_ID"
4
5export default function SubscriptionManager() {
6 const [loading, setLoading] = useState(true);
7
8 useEffect(() => {
9 if (window.og?.smi) {
10 // if the script has already been loaded, we don't need to load it again, since the global objects have already been populated
11 // reset the SM data store
12 window.og.smi.reset();
13 setLoading(false);
14 return;
15 }
16
17 // load the OG SM script
18 const script = document.createElement("script");
19 script.src = `https://static.ordergroove.com/${MERCHANT_ID}/msi.js`;
20 script.async = true;
21 script.onload = () => setLoading(false);
22 document.body.appendChild(script);
23
24 return () => {
25 document.body.removeChild(script);
26 };
27 }, []);
28
29 return (
30 <>
31 <h1>SM</h1>
32 {loading ? <p>Loading...</p> : <og-smi></og-smi>}
33 </>
34 );
35}