SolidJSS
SolidJS2y ago
29 replies
ChrisThornham

Trouble With onCleanup()

I'm building a checkout flow with Stripe's embedded checkout form. It works like this.

The user clicks a "Buy Now" button on a products page that navigates to a checkout page.

The checkout page:

- Gets the product ID and quantity from the search params.
- Gets the checkout form from stripe
- Mounts the checkout form.

This works the first time I click a buy now button.

BUT

If I click back to the products page and click another buy now button, the checkout form doesn't load.

I'm getting an error from Stripe:

"You cannot have multiple embedded checkout items."

So, how do I "clear" or unmount the checkout form when I click the back button? I want to start fresh each time I click a buy now button. My use of onCleanup (below) isn't working.

Here's my checkout page:

export default function CheckoutPage() {

  const [searchParams] = useSearchParams();

  // ref
  let checkoutElement: HTMLDivElement;

  createEffect(async () => {
    // extract the search params
    const itemsArray = [
      {
        price: searchParams.priceId,
        quantity: searchParams.qty,
      },
    ];

    // Stripe Stuff
    // Create a checkout session
    const response = await fetch("api/stripe/create-checkout-session", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        items: itemsArray,
      }),
    });
    
    // Create checkout form
    const { clientSecret } = await response.json();
    const checkout = await stripe?.initEmbeddedCheckout({
      clientSecret,
    });

    // Mount form
    if (checkoutElement) {
      checkout?.mount(checkoutElement);
    }

    // unmount the form
    onCleanup(() => {
      checkout?.unmount();
    });
  });

  return (
    <MainLayout>
      <div
        id="checkout"
        ref={(el) => checkoutElement = el}
        class="px-6 py-20 bg-[#0f151d]"
      >
        {/* Checkout will insert payment form here */}
      </div>
    </MainLayout>
  );
}
Was this page helpful?