Custom cart method in Hydrogen
This recipe implements custom cart methods in Hydrogen using the Storefront API's
variantBySelectedOptions query to let customers edit product options directly
within the cart. They'll be able to change product variants (like size and color)
without having to remove items, select different variants, and then add them to
the cart again. Their cart updates will happen automatically, without requiring
a full page refresh.
Key features:
- Custom cart method
updateLineByOptionsfor variant selection - Inline dropdown selectors for each product option in cart
- Automatic cart updates when options are changed
- Full TypeScript support with proper type augmentation
Anchor to RequirementsRequirements
- Basic understanding of Hydrogen cart implementation
- Familiarity with GraphQL and TypeScript
- Knowledge of React Router actions and forms
- GraphQL codegen must be run after applying the recipe
Anchor to Step 1: Document custom cart methods in the READMEStep 1: Document custom cart methods in the README
Update the README file with custom cart method documentation and an implementation guide.
File
Anchor to Step 2: Let customers change variants directly in the cartStep 2: Let customers change variants directly in the cart
Add variant selector functionality to cart line items for changing product options.
File
Anchor to Step 3: Add updateLineByOptions method to cart contextStep 3: Add update Line By Options method to cart context
Extend HydrogenCart context with updateLineByOptions method for variant switching.
File
Anchor to Step 4: Query product options for variant selectionStep 4: Query product options for variant selection
Add product options to cart fragments and create PRODUCT_VARIANT_QUERY for fetching variants.
Anchor to Step 5: Handle variant updates in the cart routeStep 5: Handle variant updates in the cart route
Implement the CustomUpdateLineByOptions action handler for processing variant changes in cart.