|
1
|
--- |
|
2
|
tags: |
|
3
|
- region |
|
4
|
- storefront |
|
5
|
products: |
|
6
|
- region |
|
7
|
--- |
|
8
|
|
|
9
|
import { CodeTabs, CodeTab } from "docs-ui" |
|
10
|
|
|
11
|
export const metadata = { |
|
12
|
title: `Region React Context in Storefront`, |
|
13
|
} |
|
14
|
|
|
15
|
# {metadata.title} |
|
16
|
|
|
17
|
In this guide, you'll learn how to create a region context in your React storefront. |
|
18
|
|
|
19
|
## Why Create a Region Context? |
|
20
|
|
|
21
|
Throughout your storefront, you'll need to access the customer's selected region to perform different actions, such as retrieve product's prices in the selected region. |
|
22
|
|
|
23
|
<Note title="Tip"> |
|
24
|
|
|
25
|
To learn how to allow customers to select their region, refer to the [Store Selected Region in Storefront](../store-retrieve-region/page.mdx) guide. |
|
26
|
|
|
27
|
</Note> |
|
28
|
|
|
29
|
So, if your storefront is React-based, create a region context and add it at the top of your components tree. Then, you can access the selected region anywhere in your storefront. |
|
30
|
|
|
31
|
--- |
|
32
|
|
|
33
|
## Create Region Context Provider |
|
34
|
|
|
35
|
For example, create the following file that exports a `RegionProvider` component and a `useRegion` hook: |
|
36
|
|
|
37
|
<Note title="Tip"> |
|
38
|
|
|
39
|
Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../js-sdk/page.mdx). |
|
40
|
|
|
41
|
</Note> |
|
42
|
|
|
43
|
export const highlights = [ |
|
44
|
["13", "region", "Expose region to children of the context provider."], |
|
45
|
["14", "setRegion", "Allow the context provider's children to change the selected region."], |
|
46
|
["25", "RegionProvider", "The provider component to use in your component tree."], |
|
47
|
["31", "", "If a region is set, set its ID in the local storage again in case it changed."], |
|
48
|
["38", "regionId", "Retrieve the selected region from the `localStorage`."], |
|
49
|
["41", "list", "If no region is selected, retrieve the list of regions from the Medusa application and select the first one."], |
|
50
|
["47", "retrieve", "If a region is selected, retrieve it from the Medusa application."], |
|
51
|
["64", "useRegion", "The hook that child components of the provider use to access the region."] |
|
52
|
] |
|
53
|
|
|
54
|
```tsx highlights={highlights} |
|
55
|
"use client" // include with Next.js 13+ |
|
56
|
|
|
57
|
import { |
|
58
|
createContext, |
|
59
|
useContext, |
|
60
|
useEffect, |
|
61
|
useState, |
|
62
|
} from "react" |
|
63
|
import { HttpTypes } from "@medusajs/types" |
|
64
|
import { sdk } from "@/lib/sdk" |
|
65
|
|
|
66
|
type RegionContextType = { |
|
67
|
region?: HttpTypes.StoreRegion |
|
68
|
setRegion: React.Dispatch< |
|
69
|
React.SetStateAction<HttpTypes.StoreRegion | undefined> |
|
70
|
> |
|
71
|
} |
|
72
|
|
|
73
|
const RegionContext = createContext<RegionContextType | null>(null) |
|
74
|
|
|
75
|
type RegionProviderProps = { |
|
76
|
children: React.ReactNode |
|
77
|
} |
|
78
|
|
|
79
|
export const RegionProvider = ({ children }: RegionProviderProps) => { |
|
80
|
const [region, setRegion] = useState< |
|
81
|
HttpTypes.StoreRegion |
|
82
|
>() |
|
83
|
|
|
84
|
useEffect(() => { |
|
85
|
if (region) { |
|
86
|
// set its ID in the local storage in |
|
87
|
// case it changed |
|
88
|
localStorage.setItem("region_id", region.id) |
|
89
|
return |
|
90
|
} |
|
91
|
|
|
92
|
const regionId = localStorage.getItem("region_id") |
|
93
|
if (!regionId) { |
|
94
|
// retrieve regions and select the first one |
|
95
|
sdk.store.region.list() |
|
96
|
.then(({ regions }) => { |
|
97
|
setRegion(regions[0]) |
|
98
|
}) |
|
99
|
} else { |
|
100
|
// retrieve selected region |
|
101
|
sdk.store.region.retrieve(regionId) |
|
102
|
.then(({ region: dataRegion }) => { |
|
103
|
setRegion(dataRegion) |
|
104
|
}) |
|
105
|
} |
|
106
|
}, [region]) |
|
107
|
|
|
108
|
return ( |
|
109
|
<RegionContext.Provider value={{ |
|
110
|
region, |
|
111
|
setRegion, |
|
112
|
}}> |
|
113
|
{children} |
|
114
|
</RegionContext.Provider> |
|
115
|
) |
|
116
|
} |
|
117
|
|
|
118
|
export const useRegion = () => { |
|
119
|
const context = useContext(RegionContext) |
|
120
|
|
|
121
|
if (!context) { |
|
122
|
throw new Error("useRegion must be used within a RegionProvider") |
|
123
|
} |
|
124
|
|
|
125
|
return context |
|
126
|
} |
|
127
|
``` |
|
128
|
|
|
129
|
The `RegionProvider` handles retrieving the selected region from the Medusa application, and updating its ID in the `localStorage`. |
|
130
|
|
|
131
|
The `useRegion` hook returns the value of the `RegionContext`. Child components of `RegionProvider` use this hook to access `region` or `setRegion`. |
|
132
|
|
|
133
|
--- |
|
134
|
|
|
135
|
## Use RegionProvider in Component Tree |
|
136
|
|
|
137
|
To use the region context's value, add the `RegionProvider` high in your component tree. |
|
138
|
|
|
139
|
For example, if you're using Next.js, add it to the `app/layout.tsx` or `src/app/layout.tsx` file: |
|
140
|
|
|
141
|
```tsx title="app/layout.tsx" collapsibleLines="1-14" highlights={[["22"]]} |
|
142
|
import type { Metadata } from "next" |
|
143
|
import { Inter } from "next/font/google" |
|
144
|
import "./globals.css" |
|
145
|
import { CartProvider } from "@/providers/cart" |
|
146
|
import { RegionProvider } from "@/providers/region" |
|
147
|
|
|
148
|
const inter = Inter({ subsets: ["latin"] }) |
|
149
|
|
|
150
|
export const metadata: Metadata = { |
|
151
|
title: "Create Next App", |
|
152
|
description: "Generated by create next app", |
|
153
|
} |
|
154
|
|
|
155
|
export default function RootLayout({ |
|
156
|
children, |
|
157
|
}: Readonly<{ |
|
158
|
children: React.ReactNode; |
|
159
|
}>) { |
|
160
|
return ( |
|
161
|
<html lang="en"> |
|
162
|
<body className={inter.className}> |
|
163
|
<RegionProvider> |
|
164
|
{/* Other providers... */} |
|
165
|
{children} |
|
166
|
</RegionProvider> |
|
167
|
</body> |
|
168
|
</html> |
|
169
|
) |
|
170
|
} |
|
171
|
``` |
|
172
|
|
|
173
|
### Use useRegion Hook |
|
174
|
|
|
175
|
Now, you can use the `useRegion` hook in child components of `RegionProvider`. |
|
176
|
|
|
177
|
For example: |
|
178
|
|
|
179
|
```tsx |
|
180
|
"use client" // include with Next.js 13+ |
|
181
|
// ... |
|
182
|
import { useRegion } from "@/providers/region" |
|
183
|
|
|
184
|
export default function Products() { |
|
185
|
const { region } = useRegion() |
|
186
|
// ... |
|
187
|
} |
|
188
|
``` |
|
189
|
|
|
190
|
--- |
|
191
|
|
|
192
|
## Managing Regions in Server Components |
|
193
|
|
|
194
|
For SEO and performance reasons, many components in your storefront may be server components that don't have access to client-side context. Here are patterns for managing region data in server components: |
|
195
|
|
|
196
|
### URL-Based Region Selection |
|
197
|
|
|
198
|
Store the selected region in the URL path or query parameters to make it available to server components: |
|
199
|
|
|
200
|
```tsx title="app/[countryCode]/products/page.tsx" |
|
201
|
import { sdk } from "@/lib/sdk" |
|
202
|
import { cache } from "react" |
|
203
|
|
|
204
|
// Server-side region retrieval |
|
205
|
const getRegionByCountryCode = cache(async (countryCode: string) => { |
|
206
|
const { regions } = await sdk.store.region.list({ |
|
207
|
fields: "*countries", |
|
208
|
}) |
|
209
|
|
|
210
|
return regions.find((region) => |
|
211
|
region.countries?.some((country) => |
|
212
|
country.iso_2.toLowerCase() === countryCode.toLowerCase() |
|
213
|
) |
|
214
|
) |
|
215
|
}) |
|
216
|
|
|
217
|
type Props = { |
|
218
|
params: { countryCode: string } |
|
219
|
} |
|
220
|
|
|
221
|
export default async function ProductsPage({ params }: Props) { |
|
222
|
const region = await getRegionByCountryCode(params.countryCode) |
|
223
|
|
|
224
|
if (!region) { |
|
225
|
// Handle region not found |
|
226
|
return <div>Region not found</div> |
|
227
|
} |
|
228
|
|
|
229
|
// Use region to fetch region-specific data |
|
230
|
const { products } = await sdk.store.product.list({ |
|
231
|
region_id: region.id, |
|
232
|
}) |
|
233
|
|
|
234
|
return ( |
|
235
|
<div> |
|
236
|
<h1>Products for {region.name}</h1> |
|
237
|
{/* Server-rendered product list */} |
|
238
|
</div> |
|
239
|
) |
|
240
|
} |
|
241
|
``` |
|
242
|
|
|
243
|
### Cookie-Based Region Persistence |
|
244
|
|
|
245
|
Store region preferences in cookies to access them in server components: |
|
246
|
|
|
247
|
```tsx title="lib/region-server.ts" |
|
248
|
import { cookies } from "next/headers" |
|
249
|
import { sdk } from "@/lib/sdk" |
|
250
|
|
|
251
|
export async function getServerRegion() { |
|
252
|
const cookieStore = cookies() |
|
253
|
const regionId = cookieStore.get("region_id")?.value |
|
254
|
|
|
255
|
if (!regionId) { |
|
256
|
// Return default region |
|
257
|
const { regions } = await sdk.store.region.list({ |
|
258
|
limit: 1, |
|
259
|
}) |
|
260
|
return regions[0] |
|
261
|
} |
|
262
|
|
|
263
|
try { |
|
264
|
const { region } = await sdk.store.region.retrieve(regionId) |
|
265
|
return region |
|
266
|
} catch { |
|
267
|
// Fallback to default if region not found |
|
268
|
const { regions } = await sdk.store.region.list({ |
|
269
|
limit: 1, |
|
270
|
}) |
|
271
|
return regions[0] |
|
272
|
} |
|
273
|
} |
|
274
|
``` |
|
275
|
|
|
276
|
Then use it in server components: |
|
277
|
|
|
278
|
```tsx title="components/ServerProductList.tsx" |
|
279
|
import { getServerRegion } from "@/lib/region-server" |
|
280
|
import { sdk } from "@/lib/sdk" |
|
281
|
|
|
282
|
export default async function ServerProductList() { |
|
283
|
const region = await getServerRegion() |
|
284
|
|
|
285
|
const { products } = await sdk.store.product.list({ |
|
286
|
region_id: region.id, |
|
287
|
}) |
|
288
|
|
|
289
|
return ( |
|
290
|
<div> |
|
291
|
{/* Server-rendered products with region-specific pricing */} |
|
292
|
{products.map((product) => ( |
|
293
|
<div key={product.id}> |
|
294
|
<h3>{product.title}</h3> |
|
295
|
{/* Display prices in region currency */} |
|
296
|
</div> |
|
297
|
))} |
|
298
|
</div> |
|
299
|
) |
|
300
|
} |
|
301
|
``` |
|
302
|
|
|
303
|
### Hybrid Approach |
|
304
|
|
|
305
|
Combine server and client components for optimal performance and user experience: |
|
306
|
|
|
307
|
```tsx title="app/products/page.tsx" |
|
308
|
import { Suspense } from "react" |
|
309
|
import ServerProductList from "@/components/ServerProductList" |
|
310
|
import ClientRegionSelector from "@/components/ClientRegionSelector" |
|
311
|
|
|
312
|
export default function ProductsPage() { |
|
313
|
return ( |
|
314
|
<div> |
|
315
|
{/* Client component for region selection */} |
|
316
|
<ClientRegionSelector /> |
|
317
|
|
|
318
|
{/* Server component for initial product rendering */} |
|
319
|
<Suspense fallback={<div>Loading products...</div>}> |
|
320
|
<ServerProductList /> |
|
321
|
</Suspense> |
|
322
|
</div> |
|
323
|
) |
|
324
|
} |
|
325
|
``` |
|
326
|
|
|
327
|
This approach provides server-side rendering for SEO while maintaining client-side interactivity for region switching. |