oedotme / generouted

Generated file-based routes for Vite
https://stackblitz.com/github.com/oedotme/generouted/tree/main/explorer
MIT License
1.02k stars 47 forks source link

Is it possible to define a global loader function using generouted with react-router? #167

Closed atresnjo closed 3 months ago

atresnjo commented 3 months ago

Basically, I want to protect my routes and Loader seems the best way to do it, just wondering is it possible to define the loader once and re-use it across routes? Thanks for the library! Great work 👍

export async function Loader() {
    try {
        const data = await trpcClient.authTestRouter.session.fetch()

        const user: User = {
            ...data,
        }
        return { user }
    } catch (error) {
        return new Response('Unauthorized', {
            status: 302,
            headers: { location: '/auth/sign-up' },
        })
    }
}
oedotme commented 3 months ago

@atresnjo Yes, that's possible. You can define this Loader as a global Loader by adding it to the src/pages/_app.tsx layout file similar to the global Pending and Catch defined in this react-router example.

If you need a Loader at a smaller scope, you can add it to a parent regular layout or a pathless layout group.

Hope that helps!

atresnjo commented 3 months ago

thanks! got it working with the _layout in my pathless layout group, but then had to pass the data to my outlet context and use useOutletContext to access it, works!