T
TanStack2y ago
wise-white

Basic router question on routing outside of context

Hello, I'm trying to use router.navigate({ to: '/dashboard', replace: true }); by importing router outside of the useNavigate context. This is because I want my auth listener to handling routing to/from login state and this lives in main.tsx at the parent level of RouterProvider. My question is, is it safe to just import router and call router.navigate({ to: '/dashboard', replace: true }); right away or should I check for any kind of initialization or existence before calling navigate right away? Also if there is a better way to handle this I would appreciate any help, this is how my code is set up currently main.tsx has
const renderApp = () => {
return (
<React.StrictMode>
<App>
<RouterProvider router={router} />
</App>
</React.StrictMode>
)
}
const renderApp = () => {
return (
<React.StrictMode>
<App>
<RouterProvider router={router} />
</App>
</React.StrictMode>
)
}
app.tsx has
function App({ children }: AppProps) {
useAuthStatus();

return (
<I18n>
<ThemeProvider theme={darkMode}>
<CssBaseline />
<ToastContainer
position="top-center"
autoClose={8000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
/>
{children}
</ThemeProvider>
</I18n>
);
}
function App({ children }: AppProps) {
useAuthStatus();

return (
<I18n>
<ThemeProvider theme={darkMode}>
<CssBaseline />
<ToastContainer
position="top-center"
autoClose={8000}
hideProgressBar={false}
newestOnTop={false}
closeOnClick
rtl={false}
pauseOnFocusLoss
draggable
pauseOnHover
theme="light"
/>
{children}
</ThemeProvider>
</I18n>
);
}
my problem originally was this one https://github.com/TanStack/router/issues/902 which is why I have to pass in the RouterProvider in from main into app (since I can't declare it in App without HMR Vite breaking)
GitHub
Vite HMR breaks the router · Issue #902 · TanStack/router
Describe the bug If a route is imported into the router file, and the router is first imported into another component (i.e. App.tsx) and this other component is rendered with React root.render, tri...
1 Reply
fair-rose
fair-rose2y ago
"My question is, is it safe to just import router and call router.navigate({ to: '/dashboard', replace: true })" I think so, yes.

Did you find this page helpful?