Add a marketplace-level cart to product pages
You've created a marketplace with buyer-facing pages that include product descriptions and a Buy Now button that redirects users to a merchant's online store for checkout. However, if buyers see something they want, they need to leave the marketplace to purchase the product individually. You want to remove that friction from the commerce experience. Instead, buyers should be able to select items for purchase while continuing to browse the marketplace.
In this tutorial, you'll start adding cart functionality that supports storing items from different shops. You'll add an Add to Cart button to product description pages. You'll also create an icon for a marketplace-level cart with a badge showing the total number of items in the cart.
What you'll learn
After finishing this tutorial, you'll know how to do the following:
Add line items to a cart using the cartLinesAdd mutation
Create and manage multi-shop carts using local storage
Add a cart icon to the marketplace with a badge displaying the number of items in the cart
- You've completed the product description tutorials.
Step 1: Create helpers and mutations
In this step, you'll add helper functions to call the mutations for creating the cart and adding line items to it. You'll add logic to locally store the cart IDs associated with each shop from which a buyer selects an item. You'll add a function for creating a cart and opening a new tab to checkout. You'll also add logic to get and store the number of items in the cart.
At your project root, create a
helpersfolder and add a
helpers/cartHelpers.js, add the following code.
In a subsequent tutorial, you'll build a multi-merchant cart page.
When you create the checkout, you can pass in a
countryCodeto ensure a consistent currency across all carts that are created. Otherwise, the cart currency would be in the shop's default currency, which may not be the same across shops.
Step 2: Create the cart, icon, and badge
In this step, you'll get the cart count and store it in the
Page component's state. You'll add an event listener to listen to any storage events and update the cart page accordingly, so that you always have an updated cart count in local storage. You'll also add the cart icon, with a badge to display the number of items in the cart.
components/page.js, add the following code:
Your homepage should look like the following:
Your shop page should look like the following:
Step 3: Add the ADD TO CART button
pages/products/[shopid]/[productHandle].js, add an ADD TO CART button and clean up the file to use the helper functions that you created in
Your product page should look like the following:
- Learn how to create multi-shop cart pages to display the items in the cart and the estimated cost associated with the cart.