Raw
1 ---
2 tags:
3 - cart
4 - storefront
5 products:
6 - cart
7 ---
8
9 import { CodeTabs, CodeTab } from "docs-ui"
10
11 export const metadata = {
12 title: `Create Cart Context in Storefront`,
13 }
14
15 # {metadata.title}
16
17 In this guide, you'll learn how to create a cart context in your storefront.
18
19 ## Why Create a Cart Context?
20
21 Throughout your storefront, you'll need to access the customer's cart to perform different actions. For example, you may need to add a product variant to the cart from the product page.
22
23 So, if your storefront is React-based, create a cart context and add it at the top of your components tree. Then, you can access the customer's cart anywhere in your storefront.
24
25 ---
26
27 ## Create Cart Context Provider
28
29 For example, create the following file that exports a `CartProvider` component and a `useCart` hook:
30
31 <Note title="Tip">
32
33 - This example uses the `useRegion` hook defined in the [Region React Context guide](../../regions/context/page.mdx) to associate the cart with the customer's selected region.
34 - Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx).
35
36 </Note>
37
38 export const highlights = [
39 ["14", "cart", "Expose cart to children of the context provider."],
40 ["15", "setCart", "Allow the context provider's children to update the cart."],
41 ["18", "refreshCart", "Allow the context provider's children to unset and reset the cart."],
42 ["27", "CartProvider", "The provider component to use in your component tree."],
43 ["31", "useRegion", "Use the `useRegion` hook defined in the Region Context guide."],
44 ["41", "create", "If the customer doesn't have a cart, create a new one."],
45 ["50", "retrieve", "Retrieve the customer's cart."],
46 ["57", "refreshCart", "This function unsets the cart, which triggers the `useEffect` callback to create a cart."],
47 ["73", "useCart", "The hook that child components of the provider use to access the cart."]
48 ]
49
50 ```tsx highlights={highlights}
51 "use client" // include with Next.js 13+
52
53 import {
54 createContext,
55 useContext,
56 useEffect,
57 useState,
58 } from "react"
59 import { HttpTypes } from "@medusajs/types"
60 import { useRegion } from "./region"
61 import { sdk } from "@/lib/sdk"
62
63 type CartContextType = {
64 cart?: HttpTypes.StoreCart
65 setCart: React.Dispatch<
66 React.SetStateAction<HttpTypes.StoreCart | undefined>
67 >
68 refreshCart: () => void
69 }
70
71 const CartContext = createContext<CartContextType | null>(null)
72
73 type CartProviderProps = {
74 children: React.ReactNode
75 }
76
77 export const CartProvider = ({ children }: CartProviderProps) => {
78 const [cart, setCart] = useState<
79 HttpTypes.StoreCart
80 >()
81 const { region } = useRegion()
82
83 useEffect(() => {
84 if (cart || !region) {
85 return
86 }
87
88 const cartId = localStorage.getItem("cart_id")
89 if (!cartId) {
90 // create a cart
91 sdk.store.cart.create({
92 region_id: region.id,
93 })
94 .then(({ cart: dataCart }) => {
95 localStorage.setItem("cart_id", dataCart.id)
96 setCart(dataCart)
97 })
98 } else {
99 // retrieve cart
100 sdk.store.cart.retrieve(cartId)
101 .then(({ cart: dataCart }) => {
102 setCart(dataCart)
103 })
104 }
105 }, [cart, region])
106
107 const refreshCart = () => {
108 localStorage.removeItem("cart_id")
109 setCart(undefined)
110 }
111
112 return (
113 <CartContext.Provider value={{
114 cart,
115 setCart,
116 refreshCart,
117 }}>
118 {children}
119 </CartContext.Provider>
120 )
121 }
122
123 export const useCart = () => {
124 const context = useContext(CartContext)
125
126 if (!context) {
127 throw new Error("useCart must be used within a CartProvider")
128 }
129
130 return context
131 }
132 ```
133
134 The `CartProvider` handles retrieving or creating the customer's cart. It uses the `useRegion` hook defined in the [Region Context guide](../../regions/context/page.mdx) to associate the cart with the customer's selected region.
135
136 The `useCart` hook returns the value of the `CartContext`. Child components of `CartProvider` use this hook to access `cart`, `setCart`, or `refreshCart`.
137
138 `refreshCart` unsets the cart, which triggers the `useEffect` callback to create a cart. This is useful when the customer logs in or out, or after the customer places an order.
139
140 <Note title="Tip">
141
142 You can add to the context and provider other functions useful for updating the cart and its items. Refer to the following guides for details on how to implement these functions:
143
144 - [Manage Cart Items](../manage-items/page.mdx).
145 - [Update Cart's Region and Customer](../update/page.mdx).
146
147 </Note>
148
149 ---
150
151 ## Use CartProvider in Component Tree
152
153 To use the cart context's value, add the `CartProvider` high in your component tree.
154
155 For example, if you're using Next.js, add it to the `app/layout.tsx` or `src/app/layout.tsx` file:
156
157 ```tsx title="app/layout.tsx" collapsibleLines="1-14" highlights={[["23"]]}
158 import type { Metadata } from "next"
159 import { Inter } from "next/font/google"
160 import "./globals.css"
161 import { CartProvider } from "@/providers/cart"
162 import { RegionProvider } from "@/providers/region"
163
164 const inter = Inter({ subsets: ["latin"] })
165
166 export const metadata: Metadata = {
167 title: "Create Next App",
168 description: "Generated by create next app",
169 }
170
171 export default function RootLayout({
172 children,
173 }: Readonly<{
174 children: React.ReactNode;
175 }>) {
176 return (
177 <html lang="en">
178 <body className={inter.className}>
179 <RegionProvider>
180 <CartProvider>
181 {/* Other providers... */}
182 {children}
183 </CartProvider>
184 </RegionProvider>
185 </body>
186 </html>
187 )
188 }
189 ```
190
191 Make sure to put the `CartProvider` as a child of the `RegionProvider` since it uses the `useRegion` hook defined in the [Region Context guide](../../regions/context/page.mdx).
192
193 ### Use useCart Hook
194
195 Now, you can use the `useCart` hook in child components of `CartProvider`.
196
197 For example:
198
199 ```tsx
200 "use client" // include with Next.js 13+
201 // ...
202 import { useCart } from "@/providers/cart"
203
204 export default function Products() {
205 const { cart } = useCart()
206 // ...
207 }
208 ```
209
210 The `useCart` hook returns the cart details, which you can use in your components.