I am trying to implement routing in to my application with react-router-dom
V6 using the new createBrowserRouter
function and RouterProvider
component.
When trying to implement a loader
(see routes themeLoader
), the loader is always fired as soon as the router
is created (see App.tsx).
Granted this only happens on the theme
route as it should, but as it is firing at such an early stage it is being triggered before the authentication has started let alone completed and the queries it calls require an authenticate user.
Is it possible to delay the loader
until authentication has completed?
I have tried shouldRevalidate
but this does not prevent the loader
from firing the first time.
// PrivateRoute.tsx
function PrivateRoute(Props: PrivateRouteProps) {
console.log('PrivateRoute!');
// Auth logic here
if (isAuthenticating) return <div>Authenticating...</div>;
return !isUnauthorised ? <Outlet /> : <div>{'Unauthorised Access'}</div>;
}
// Theme.tsx
export async function themeLoader({ params }: LoaderProps) {
console.log('themeLoader!');
const query = store.dispatch(getTheme(params.theme));
const { data: theme } = await query;
query.unsubscribe();
if (theme === undefined)
throw new Response('Theme Not Found', { status: 404 });
return theme;
}
// Routes
const themeRoute = {
path: 'themes/:theme',
element: <ThemePage />,
loader: themeLoader
};
const parentRoute = {
path: '/',
element: <PrivateRoute authorisedRoles={MemberRoles} />,
errorElement: <RouteBoundary />,
children: [themeRoute]
};
// App.tsx
const router = createBrowserRouter([parentRoute]);
// themeLoader fires at this point...
function App() {
console.log('App!');
return <RouterProvider router={router} />;
}
// Console Output
themeLoader!
App!
RouteBoundary!
// Expected Output
App!
PrivateRoute!
themeLoader!
No, you cant.
Loaders are called in parallel, so they cannot block each other or provide each other data.
https://github.com/remix-run/react-router/issues/9188#issuecomment-1248180434
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With