How to make beforeLoad hook run once in root route in Tanstack Start?
Hey there. As the title says, I have a beforeLoad hook in root route which returns the user session and color theme in the context, which I use in another pathless (_authed) file to redirect the unauthenticated users. The thing is that for example, when I am trying to navigate from /settings/profile to /settings/security, this beforeLoad hook runs again on the client. Every single route match triggers this hook. So far, I tried some properties from tanstack router such as (staleTime, gcTime, shouldReload), but did not work around. It seems like they only work with the loader() hook.
11 Replies
genetic-orange•7mo ago
you cant disable it to run
if you have some data fetching there, you should cache it using e.g. query
tame-yellowOP•7mo ago
how can i work around this without using tanstack query etc.? I think I can replace the following with useLoaderData, but I believe I will not be able to use the context in the pathless (_authed) route, so should I fetch these data again there? @Manuel Schiller
genetic-orange•7mo ago
why not use query?
i guess you need to handle session invalidation at some time anyhow?
tame-yellowOP•7mo ago
It seemed unnecessary to add tanstack query. I handled session invalidations by just using router.invalidate()
genetic-orange•7mo ago
yeah but how do you know when to invalidate?
i mean timeouts etc
you can of course build your own cache but I would just use query here
there is right now no way to not run beforeLoad
tame-yellowOP•7mo ago
Thank you for quick response. Do you think it would make sense to have this feature for future? I would like to create a feature request on GitHub
genetic-orange•7mo ago
how would router know to not run beforeLoad?
how would that be configured?
tame-yellowOP•7mo ago
maybe the same as the one for loader() hook, shouldReload property exists to manage this for subsequent route matches.
idk about the possibility though
genetic-orange•7mo ago
i dont know if we would / should add this. but for sure create the feature request
xenial-black•6mo ago
How would you invalidate a session that was using query? route.invalidate() has no effect since the data is cached by react-query, queryClient.invalidateQueries() seems to have no effect as its doesnt seem to update the context
genetic-orange•6mo ago
probably it's best to provide a complete minimal example for easier debuggign