How to Use _addToCart Method#
The _addToCart method adds a specified product variant to the user's shopping cart. It manages the cart token and updates local storage with the latest cart data. It is fire-and-forget: it returns nothing, so you cannot await it. When you need the result, use _addToCartAsync, which takes the same parameters and returns a promise.Usage Steps:#
1.
The method takes four parameters:productId: The unique identifier of the product you want to add.
variantId: The unique identifier of the product variant.
quantity: The quantity of the product variant to add.
productVariant (optional): The variant object. Its price and initialPrice are sent with the Google Analytics addToCart event.
2.
Call _addToCart with the parameters when you don't need to wait for the result, or await this._addToCartAsync(...) when you do.
3.
_addToCart reports the result only through the "cart-changed" event.
_addToCartAsync resolves with the updated cart. It never rejects: if the request fails, it resolves with the error response instead of the cart.
Example:#
Common Use Cases:#
1.
This method is used to add products to the shopping cart from various parts of your application, such as product detail pages, product listings, or quick view modals.
2.
For authenticated users without a cart token, the method requests the user's cart token. _addToCart does not wait for that request before adding the item, so prefer _addToCartAsync when the add may be the user's first cart action.
3.
Updating Cart State and UI:The method updates the cart in local storage and emits a "cart-changed" event, which can trigger UI updates or other actions related to cart changes, like updating the cart icon or displaying a notification.
Notes:#
Return Value: _addToCart returns nothing. _addToCartAsync returns a promise that resolves with the updated cart, or, if something fails, with the HTTP error response (undefined when the failure was not an HTTP error).
Error Handling: _addToCartAsync catches request errors and resolves with the error response, so check the result instead of wrapping the call in try/catch.
Local Storage Management: The method manages local storage to ensure the cart state is maintained across different parts of the application and between sessions.
Event Emission: After updating the cart, the method emits a "cart-changed" event, allowing other parts of the application to react to the cart update.
This method provides a robust and efficient way to add items to the shopping cart, handle authentication, and manage cart state in an e-commerce application.Modified at 2026-10-07 12:01:58