Shopify / storefront-api-examples

Example custom storefront applications built on Shopify's Storefront API
https://help.shopify.com/api/storefront-api
MIT License
1.12k stars 329 forks source link

Question: Why checkoutLineItemsReplace? #107

Closed cjkihl closed 4 years ago

cjkihl commented 4 years ago

What is the main reason why checkoutLineItemsAdd, checkoutLineItemsRemove and checkoutLineItemsUpdate is deprecated in favour for checkoutLineItemsReplace.

Does checkoutLineItemsReplace replace all line items that are currently on the server?

tristan-potter commented 4 years ago

Yes, checkoutLineItemsReplace will replace all line items.

Mutating previously created/updated line items is not always possible, so the -Add -Remove and -Update mutations were sometimes unable to find previously added or updated line items.

The -Replace mutation provides a consistent interface for modifying line items on a checkout.

cjkihl commented 4 years ago

Ok, I see.

Wouldn't this cause problems when you're using the API in different tabs?

When I shop on Amazon, for example, I have multiple tabs open and comparing products.

  1. In Tab 1 I add a product to cart.
  2. Switch to Tab 2.
  3. Tab 2 is now out of sync. It says no products in the cart.
  4. In Tab 2 I add a product to the cart.
  5. Tab 2 Now says there are 2 products in the cart. (Carts got merged on the Amazon server)

With checkoutLineItemsReplace the previous cart on the server from tab 1 would be overwritten.

tristan-potter commented 4 years ago

Yes, that would be a problem if you were using the checkout object as the source of truth for a cart. To get around this you could query the checkout object first before making any changes; however, we recommend that you don't use checkouts as carts for performance reasons (checkout mutations have to do a lot of verification work).

Instead we recommend keeping the variant IDs and quantities in the browser's localStorage (which will be synced between your tabs so long as they're all the same domain), and update them when the user takes any relevant actions (add/remove a variant or update quantity). Then when the user is ready to begin checking out (or you want to display discounts or shipping rates) use the stored variant ID's and quantities in the checkout mutations.

If you have more questions on how to implement carts, our forums have some posts on the topic already, and will be more useful for getting answers to any use-case-specific questions you have.

cjkihl commented 4 years ago

Great, I understand. Thank you for the help! I'll continue the discussion on the forum 🙂