Accessing request from any server component in Deno Fresh
Tea Reggi
Posted on October 29, 2022
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/>
)
})
💖 💪 🙅 🚩
Tea Reggi
Posted on October 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
webdev Understanding HTTP, Cookies, Email Protocols, and DNS: A Guide to Key Internet Technologies
November 30, 2024