Back to Medusa

{metadata.title}

www/apps/resources/app/storefront-development/cart/retrieve/page.mdx

2.14.23.5 KB
Original Source

import { CodeTabs, CodeTab } from "docs-ui"

export const metadata = { title: Retrieve Cart in Storefront, }

{metadata.title}

In this guide, you'll learn how to retrieve a cart's details in your storefront.

Assuming you stored the cart's ID in the localStorage as explained in the Create Cart guide, you can retrieve a cart by sending a request to the Get a Cart API route.

For example:

<CodeTabs group="store-request"> <CodeTab label="React" value="react">

export const highlights = [ ["17", "cartId", "Retrieve the cart ID from localStorage."], ["19", "TODO", "You can create the cart and set it here as explained in the Create Cart guide."], ["29", "formatPrice", "This function was previously created to format product prices. You can re-use the same function."], ["32", "currency", "If you reuse the formatPrice function, pass the currency code as a parameter."], ]

tsx
"use client" // include with Next.js 13+

import { useEffect, useState } from "react"
import { HttpTypes } from "@medusajs/types"
import { sdk } from "@/lib/sdk"

export default function Cart() {
  const [cart, setCart] = useState<
    HttpTypes.StoreCart
  >()

  useEffect(() => {
    if (cart) {
      return
    }

    const cartId = localStorage.getItem("cart_id")
    if (!cartId) {
      // TODO create cart
      return
    }

    sdk.store.cart.retrieve(cartId)
    .then(({ cart: dataCart }) => {
      setCart(dataCart)
    })
  }, [cart])

  const formatPrice = (amount: number): string => {
    return new Intl.NumberFormat("en-US", {
      style: "currency",
      currency: cart?.currency_code,
    })
    .format(amount)
  }

  return (
    <div>
      {!cart && <span>Loading...</span>}
      {cart && (
        <>
          <span>Cart ID: {cart.id}</span>
          <ul>
            {cart.items?.map((item) => (
              <li key={item.id}>
                {item.title} -
                Quantity: {item.quantity} -
                Price: {formatPrice(item.unit_price)}
              </li>
            ))}
          </ul>
          <span>Cart Total: {formatPrice(cart.total)}</span>
        </>
      )}
    </div>
  )
}
</CodeTab> <CodeTab label="JS SDK" value="js-sdk">

export const fetchHighlights = [ ["1", "cartId", "Pass the customer's cart ID as a parameter."], ]

ts
sdk.store.cart.retrieve(cartId)
.then(({ cart }) => {
  // use cart...
  console.log(cart)
})
</CodeTab> </CodeTabs>

In this example, you retrieve a cart by sending a request to the Get a Cart API route.

The response of the Get a Cart API route has a cart field, which is a cart object.

Format Prices

When displaying the cart's totals or line item's price, make sure to format the price as implemented in the formatPrice function shown in the above snippet:

ts
const formatPrice = (amount: number): string => {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency: cart?.currency_code,
  })
  .format(amount)
}

Since this is the same function used to format the prices of product variants, you can define the function in one place and re-use it where necessary. In that case, make sure to pass the currency code as a parameter to the formatPrice function.