Shopify / hydrogen

Hydrogen lets you build faster headless storefronts in less time, on Shopify.
https://hydrogen.shop
MIT License
1.19k stars 241 forks source link

product_added_to_cart and product_removed_from_cart not firing #2026

Closed williamkhshea closed 2 weeks ago

williamkhshea commented 1 month ago

What is the location of your example repository?

No response

Which package or tool is having this issue?

Hydrogen

What version of that package or tool are you using?

2024.4.0

What version of Remix are you using?

No response

Steps to Reproduce

Subscribe 'cart_updated', 'product_added_to_cart', and 'product_removed_from_cart'. Only 'cart_updated' is firing.

subscribe('cart_updated', (data) => {
  console.log('CustomAnalytics - Cart updated:', data);
});
subscribe('product_added_to_cart', (data) => {
  console.log('CustomAnalytics - Product added to cart:', data);
});
subscribe('product_removed_from_cart', (data) => {
  console.log('CustomAnalytics - Product removed from cart:', data);
});

In CartAnalytics.tsx, it loops through cart.lines.nodes.

Screenshot 2024-04-21 at 3 46 47 PM

While the cart data returned is cart.lines.edges, and therefore product_added_to_cart and product_removed_from_cart will never fire. Screenshot 2024-04-21 at 3 49 45 PM

Expected Behavior

product_added_to_cart and product_removed_from_cart are firing.

Actual Behavior

product_added_to_cart and product_removed_from_cart are NOT firing.

wizardlyhel commented 4 weeks ago

Oh! thanks for the reporting this issue. What cart query do you have? Did you query for the cursor property?

williamkhshea commented 3 weeks ago

@wizardlyhel I subscribed to the 'cart_updated' event and inspected the cart data returned.

williamkhshea commented 3 weeks ago

@wizardlyhel Also, instead of returning previous line and current line, it would be helpful if you return the difference for add to cart and remove from cart event, just like what you did for Web pixel api.

For example, for adding 4 items of total value $40, instead of returning previous line {item: "a", quantity: 1, value: 10} and current line {item: "a", quantity: 5, value: 50}, it would be better to return {item: "a", quantity: 4, value: 40}.

wizardlyhel commented 3 weeks ago

Also, instead of returning previous line and current line, it would be helpful if you return the difference for add to cart and remove from cart event

You can create an event that can just output an update to a cart line that is a difference. This component cannot assume that a quantity difference is the default for every single analytics frameworks out there, including Shopify's own analytics requirements. It's the reason why we decided to return the previous line and the current line. So that you can calculate the difference if you need.