Remove from cart
This guide shows you 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.
RequirementsAnchor link to section titled "Requirements"
- You've completed the Fetch and read a cart and Add products to a cart guides.
Step 1: Add a remove action handlerAnchor link to section titled "Step 1: Add a remove action handler"
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
remove_from_cart condition to handle requests to remove line items from a
<ItemRemoveButton /> component.
Add a new GraphQL mutation definition (
REMOVE_LINE_ITEMS_MUTATION), which is based on the
cartLinesRemove mutation in the Storefront API:
Next, add a new
cartRemove 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
remove_from_cart condition to your existing
cartActions switch statement to route the new requests to the
cartRemove API handler:
Step 2: Create the button to remove itemsAnchor link to section titled "Step 2: Create the button to remove items"
Now that you've configured the cart route, add a button that allows you to post requests to remove line items.
Define a simple react component
<ItemRemoveButton /> 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
cartAction: A hidden field that specifies the cart mutation handler that you want to use for the requests
lineIds: The cart line IDs that you want to remove from the cart
- Learn how to read data from a cart in Hydrogen.
- Add products to a cart on the server-side using a form element and a route action to handle Storefront API requests.