Skip to content

Commit efb5289

Browse files
committed
refactor: custom hook for route data
1 parent d8c706d commit efb5289

File tree

3 files changed

+23
-7
lines changed

3 files changed

+23
-7
lines changed

examples/next/template-hierarchy/example-app/src/components/Layout.js

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
import { useContext } from "react";
2-
import { RouteDataContext } from "@/lib/context";
1+
import { useRouteData } from "@/lib/context";
32
import TemplateHierarchyInfo from "@/components/TemplateHierarchyInfo";
43

54
export default function Layout({ children }) {
6-
const { templateData, uri } = useContext(RouteDataContext);
5+
const { templateData, uri } = useRouteData();
76

87
return (
98
<div className="layout">
Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,20 @@
11
import React from "react";
22

3-
export const RouteDataContext = React.createContext();
3+
const RouteDataContext = React.createContext();
4+
5+
export const useRouteData = () => {
6+
const context = React.useContext(RouteDataContext);
7+
if (!context) {
8+
throw new Error(
9+
"useRouteData must be used within a RouteDataContext.Provider"
10+
);
11+
}
12+
return context;
13+
};
14+
export const RouteDataProvider = ({ children, value }) => {
15+
return (
16+
<RouteDataContext.Provider value={value}>
17+
{children}
18+
</RouteDataContext.Provider>
19+
);
20+
};

examples/next/template-hierarchy/example-app/src/pages/[[...uri]].js

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { uriToTemplate } from "@/lib/templateHierarchy";
2-
import { RouteDataContext } from "@/lib/context";
2+
import { RouteDataProvider } from "@/lib/context";
33
import availableTemplates from "@/wp-templates";
44

55
export default function Page(props) {
@@ -8,9 +8,9 @@ export default function Page(props) {
88
const PageTemplate = availableTemplates[templateData.template?.id];
99

1010
return (
11-
<RouteDataContext.Provider value={props}>
11+
<RouteDataProvider value={props}>
1212
<PageTemplate {...props} />
13-
</RouteDataContext.Provider>
13+
</RouteDataProvider>
1414
);
1515
}
1616

0 commit comments

Comments
 (0)