Update cart line items
This guide shows you how to update existing cart line items in Hydrogen.
Requirements
Anchor link to section titled "Requirements"- You've completed the Fetch and read a cart and Add products to a cart guides.
Step 1: Define the cart action
Anchor link to section titled "Step 1: Define the cart action"In the Add products to a cart guide, you created a route action
to handle add to cart requests from the <AddToCartButton />
form.
Now, you'll create a new update_lines
condition to handle requests to remove line items from a <UpdateCartButton/>
component.
Add a new GraphQL mutation definition (UPDATE_LINE_ITEMS_MUTATION
), which is based on the cartLinesUpdate
mutation in the Storefront API:
Next, add a new cartUpdate
Storefront API handler function using the Storefront API client provided in the request context.
To learn more about the Storefront API client and its options, refer to the Fetch data in Hydrogen guide.
Finally, add a new update_lines
condition to your existing cartActions
switch statement to route the new requests to the cartUpdate
API handler:
Step 2: Create the button to update cart line items
Anchor link to section titled "Step 2: Create the button to update cart line items"Now that you've configured the cart route, you can add a button that allows you to update cart line items.
Define a simple react component < UpdateCartButton />
with a fetcher.Form
from Remix useFetcher. Set the form method to POST
and the action to /cart
to ensure the requests point to the route action defined in Step 1.
Finally, add these hidden input fields to pass data to your action as formData
:
cartAction
: A hidden field that specifies the cart mutation handler that you want to use for the requestslines
: The cart lines that you want to update
- Learn how to read data from a cart in Hydrogen.
- Learn how to remove line items from a cart on the server-side, using a form element and a Remix route action that handles Storefront API requests.