javascriptreactjsshopifyshopify-hydrogen

Cart toast notification - Shopify Hydrogen


I managed to create onLineAdd toast notification whenever a person adds something to their cart, however, I can't seem to grasp how to show product information and show it in the toast.

What I'm looking for is onLineAdd to trigger a notification that says: "XXX (with picture) have been added to the cart." Is this possible?

My code:

const open = useCallback(() => {
    console.log("Opening product added popup, with image and title.")
}, []);

<ShopifyCartProvider
    onLineAdd={open}
    onCreate={open}>
    {children}
</ShopifyCartProvider>

It's even implemented on the official shopify hydrogen store: (Try adding something to the cart here) https://shopify.supply/products/entrepreneur-tee


Solution

  • Looking at the source code of CartProvider (link), it does not seem likely to me that this is the intended place to do such things as opening toasts with product info, otherwise i would assume the shopify devs would not simply omit passing ANY information/params to the "event"-methods, like onLineAdd (not exactly sure what is the point of those methods without any context information passed to them, but didn't dig that deep).

    Therefore I'm proposing that you look into other components, for example AddToCartButton (link) (or what are you using to trigger that onLineAdd-event?) which seems to be much more likely to provide the information you need with:

      const handleAddItem = useCallback(() => {
        setAddingItem(true);
        linesAdd([
          {
            quantity,
            merchandiseId: variantId || '',
            attributes,
            sellingPlanId,
          },
        ]);
      }, [linesAdd, quantity, variantId, attributes, sellingPlanId]);
    
      return (
        <>
          <BaseButton
            {...passthroughProps}
            disabled={disabled}
            onClick={onClick}
            defaultOnClick={handleAddItem}
          >
            {children}
          </BaseButton>
    ...
    

    so you could provide your own handleAddItem method that will open that toast of yours and then set that as the defaultOnClick prop?

    Maybe there are other components involved that could do the same?

    If you insist on doing it the same way as they did it in the official store you linked to, maybe comparing the source of CartProvider on github with what they did with it in the store (link) could shine a light on how to do it as well!

    PS: Forgive if I'm overlooking something obvious, never worked with shopify hydrogen ;)