Within Deno Fresh a route can have access to the request via an exported handler. What if you have a tree of components, and you'd like to access the request
from any point in the tree?
The code below creates a request context and provider that you can use on all your pages.
export const handler: Handlers<Request> = {
GET(request, ctx) {
return ctx.render(request);
},
POST(request, ctx) {
return ctx.render(request);
},
PUT(request, ctx) {
return ctx.render(request);
},
DELETE(request, ctx) {
return ctx.render(request);
},
};
const RequestContext = createContext(new Request('http://localhost:8000/'));
export const useRequest = () => useContext(RequestContext);
export function withRequest(Component: () => JSX.Element) {
return ({ data }: PageProps<Request>) => {
return (
<RequestContext.Provider value={data}>
{<Component/>}
</RequestContext.Provider>
)
}
}
To use in your route:
import { handler, withRequest, useRequest } from "../lib/request";
export { handler }
const Greeting = () => {
const { url } = useRequest()
return <div>{url}</div>
}
export default withRequest(() => {
return (
<Greeting/>
)
})
Top comments (0)