Learning Resources

Region Context in Storefront

Throughout your storefront, you'll need to access the selected region to perform different actions, such as retrieve product's prices in the selected region.

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.

Create Region Context Provider#

For example, create the following file that exports a RegionProvider component and a useRegion hook:

Code
1"use client" // include with Next.js 13+2
3import { 4  createContext, 5  useContext, 6  useEffect, 7  useState,8} from "react"9import { HttpTypes } from "@medusajs/types"10
11type RegionContextType = {12  region?: HttpTypes.StoreRegion13  setRegion: React.Dispatch<14    React.SetStateAction<HttpTypes.StoreRegion | undefined>15  >16}17
18const RegionContext = createContext<RegionContextType | null>(null)19
20type RegionProviderProps = {21  children: React.ReactNode22}23
24export const RegionProvider = (25  { children }: RegionProviderProps26) => {27  const [region, setRegion] = useState<28    HttpTypes.StoreRegion29  >()30
31  useEffect(() => {32    if (region) {33      // set its ID in the local storage in34      // case it changed35      localStorage.setItem("region_id", region.id)36      return37    }38
39    const regionId = localStorage.getItem("region_id")40    if (!regionId) {41      // retrieve regions and select the first one42      fetch(`http://localhost:9000/store/regions`, {43        credentials: "include",44        headers: {45          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,46        },47      })48      .then((res) => res.json())49      .then(({ regions }) => {50        setRegion(regions[0])51      })52    } else {53      // retrieve selected region54      fetch(`http://localhost:9000/store/regions/${regionId}`, {55        credentials: "include",56        headers: {57          "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,58        },59      })60      .then((res) => res.json())61      .then(({ region: dataRegion }) => {62        setRegion(dataRegion)63      })64    }65  }, [region])66
67  return (68    <RegionContext.Provider value={{69      region,70      setRegion,71    }}>72      {children}73    </RegionContext.Provider>74  )75}76
77export const useRegion = () => {78  const context = useContext(RegionContext)79
80  if (!context) {81    throw new Error("useRegion must be used within a RegionProvider")82  }83
84  return context85}

The RegionProvider handles retrieving the selected region from the Medusa application, and updating its ID in the localStorage.

The useRegion hook returns the value of the RegionContext. Child components of RegionProvider use this hook to access region or setRegion.


Use RegionProvider in Component Tree#

To use the region context's value, add the RegionProvider high in your component tree.

For example, if you're using Next.js, add it to the app/layout.tsx or src/app/layout.tsx file:

app/layout.tsx
13
14export default function RootLayout({15  children,16}: Readonly<{17  children: React.ReactNode;18}>) {19  return (20    <html lang="en">21      <body className={inter.className}>22        <RegionProvider>23          {/* Other providers... */}24          {children}25        </RegionProvider>26      </body>27    </html>28  )29}

Use useRegion Hook#

Now, you can use the useRegion hook in child components of RegionProvider.

For example:

Code
1"use client" // include with Next.js 13+2// ...3import { useRegion } from "../providers/region"4
5export default function Products() {6  const { region } = useRegion()7  // ...8}
Was this page helpful?
Edit this page