Docs
STEP 4-1

Examples that connect to the SDK

These examples only call the SDK. They don't depend on your cart or checkout handling, so in some cases you can use them without changes. Pass what connects them to your cart (CartConnector and the function that fetches the cart again) and the store ID as props of CheckoutPlusProvider (see StoreCheckoutPlus in Step 3: Initialize the SDK).

If you use React 18, unmount the banner in CheckoutPlusBanner in a useEffect cleanup (React 18 doesn't call the function returned by a ref callback), and change the last line of CheckoutPlusProvider to <CheckoutPlusContext.Provider>.

lib/checkout-plus.ts

// `lib/checkout-plus.ts` (example)
/** Waits for the SDK script to finish loading. Returns `null` if it can't be loaded because of blocking or a timeout, and your code continues without Checkout+ */
export function loadCheckoutPlus(timeoutMs = 10_000): Promise<CheckoutPlusGlobal | null> {
  const loaded = window.rcmr?.checkoutPlus // Before the SDK loads, `window.rcmr` may not exist
  if (loaded) return Promise.resolve(loaded)
  return new Promise((resolve) => {
    const done = () => {
      clearTimeout(timer)
      window.removeEventListener('recustomer-checkout-plus:ready', done)
      resolve(window.rcmr?.checkoutPlus ?? null)
    }
    const timer = setTimeout(done, timeoutMs)
    window.addEventListener('recustomer-checkout-plus:ready', done) // The SDK dispatches this event when it finishes loading
  })
}

components/CheckoutPlusProvider.tsx

// `components/CheckoutPlusProvider.tsx` (React 19 or later example)
'use client'
import {
  createContext,
  useContext,
  useEffect,
  useRef,
  useState,
  type ReactNode,
} from 'react'
import { loadCheckoutPlus } from '@/lib/checkout-plus'

const CheckoutPlusContext = createContext<CheckoutPlusSession | null>(null)

type ProviderProps = Pick<
  CheckoutPlusInitOptions,
  'locale' | 'displaySettings' | 'initialSelection' | 'onError'
> & {
  // This store's store ID
  storeId: string
  cart: CartConnector // Your `CartConnector` (Step 2)
  reloadCart: () => void | Promise<unknown> // Refetches your cart
  enabled?: boolean // While false, the SDK is not created. Defaults to true
  children: ReactNode
}

/** Wraps the part that shows the cart, and handles creating and shutting down the SDK */
export function CheckoutPlusProvider({
  storeId,
  locale,
  enabled = true,
  children,
  ...options
}: ProviderProps) {
  const [checkoutPlus, setCheckoutPlus] = useState<CheckoutPlusSession | null>(null)
  const latest = useRef(options)
  useEffect(() => {
    latest.current = options // Always call the latest callbacks
  })

  // Create the SDK, and shut it down when `CheckoutPlusProvider` goes away and when `storeId`, `locale`, or `enabled` changes
  useEffect(() => {
    if (!enabled) return
    let instance: CheckoutPlusSession | null = null
    let active = true
    void loadCheckoutPlus().then((sdk) => {
      // If the SDK can't be loaded, everything works without Checkout+
      if (sdk === null || !active) return
      // These three use the values at creation time
      const { cart, displaySettings, initialSelection } = latest.current
      instance = sdk.init({
        storeId,
        cart,
        locale,
        displaySettings,
        initialSelection,
        // Refetch the cart after the SDK adds or removes a Checkout+ product
        onCheckoutPlusLinesChange: () => {
          // The SDK does not wait for the Promise, so catch failures here. Replace this to send them to your monitoring
          Promise.resolve(latest.current.reloadCart()).catch((error: unknown) => console.error('checkout-plus: reloadCart failed', error))
        },
        // Send to your monitoring
        onError: (error) => latest.current.onError?.(error),
      })
      setCheckoutPlus(instance)
    })
    return () => {
      active = false
      instance?.destroy() // Also unmounts all banners
      setCheckoutPlus(null)
    }
  }, [storeId, locale, enabled])

  // Call it once right after init(), to remove Checkout+ products left over from the previous screen
  useEffect(() => {
    void checkoutPlus?.refresh()
  }, [checkoutPlus])

  return <CheckoutPlusContext value={checkoutPlus}>{children}</CheckoutPlusContext>
}

/** Returns the `CheckoutPlusSession`. `null` before it is created and when the SDK is unavailable */
export const useCheckoutPlus = () => useContext(CheckoutPlusContext)

components/CheckoutPlusBanner.tsx

// `components/CheckoutPlusBanner.tsx` (React 19 or later example)
'use client'
import { useCallback } from 'react'
import { useCheckoutPlus } from '@/components/CheckoutPlusProvider'

/** Shows the banner. You can place it on both the cart page and the cart drawer */
export function CheckoutPlusBanner() {
  const checkoutPlus = useCheckoutPlus()

  // React calls the function returned by the ref callback when the element is detached (React 19 or later)
  const ref = useCallback(
    (el: HTMLDivElement | null) => {
      if (el === null || checkoutPlus === null) return
      // Show the banner in the element
      const mounted = checkoutPlus.mount(el)
      return () => mounted.unmount()
    },
    [checkoutPlus],
  )

  return <div ref={ref} />
}
© Recustomer, Inc.