Repository navigation
Description
Started thinking about this because of 6606d78
Background
In #1667 (fix in #1674) we ran into a problem caused by not prefetching something in a loader when were supposed to. In theory, this is what the invariant in getUsePrefetchedApiQuery is supposed to prevent. By asserting that the data is there at query time without any intervening loading state, we guarantee that it must have been pulled from the React Query cache, which means it was already done being fetched by render time. This check has prevented potential bugs and revealed actual bugs.
The problem
However, there is something cannot check that way, and this is what went wrong in #1667/#1674. The API calls in question (current user and groups) were prefetched in a loader — userLoader and that made the invariant pass.
Lines 91 to 99 in 7327d7c
| {/* This wraps all routes that are supposed to be authenticated */} | |
| <Route loader={userLoader} errorElement={<RouterDataErrorBoundary />}> | |
| <Route path="settings" handle={{ crumb: 'settings' }} element={<SettingsLayout />}> | |
| <Route | |
| path="profile" | |
| element={<ProfilePage />} | |
| loader={ProfilePage.loader} | |
| handle={{ crumb: 'Profile' }} | |
| /> |
However, userLoader is common to all authenticated routes, and therefore does not run again when navigating from one authenticated route to another. This is a problem because of React Query's concept of cacheTime (which is rightly being renamed to gcTime in v5). At the end of the default 5 minute cacheTime, the currentUserView response sitting in RQ's cache gets deleted, so if we try to navigate to a new page that relies on that data (namely the profile page) the data is not cached and the prefetch check invariant fails. This was hard to catch because it requires waiting 5 minutes and only then navigating to profile. Our E2E tests would never catch something that takes 5 minutes to show up, and even in manual use of the dogfood rack, we didn't notice the issue for weeks.
Aside: when do loaders run?
This is a fundamental part of how React Router and Remix work: loaders only run when their route segment is new after navigation. For example, with the below route config, if you go to /a/b/c, all three relevant loaders (A, B, C) will run (in parallel). But if you then do a client-side nav to /a/b/d, only loaderD will run because segments a and b are shared between the two routes.
<Route path='a' loader={A}>
<Route path='b' loader={B}>
<Route path='c' loader={C} />
<Route path='d' loader={D} />
</Route>
</Route>What correctness looks like
Making reference to the example route config above, the basic principle is this: if page /a/b/c depends on resource R (pedantically, an API call to retrieve R), we must ensure the prefetch for R is done directly in loader C so that the data will always be prefetched and cacheTime is irrelevant. More abstractly, if prefetched data (most of our fetches are prefetched) is used at a given level in the route tree, it must be prefetched in a loader at that same level, rather than relying on a higher-up route to fetch it.
Ensuring correctness
Right now, we check this is correct manually: look with your eyeballs and make sure the relevant data is fetched in the right place. But we've made a few mistakes. It feels to me like a self-inflicted problem and the right solution would make it disappear rather than fixing it.
I have some ideas but none are rock solid.
- Disallow use of
usePrefetchedApiQuery"further down" the component tree, which makes it hard to know what data a given page component relies on. If we only make directusePrefetchedApiQuerycalls at top level in the page components, we can more easily tell whether the same things are also being prefetched in that page's loader - In the case of logic we really want to wrap up, like
useCurrentProjectRolein 6606d78, we could make it so the hook has aprefetchesfunction hanging off it that takes any relevant arguments (like a project ID) and returns a list of promises to prefetch, and we'd call it like this in the loader:Promise.all([ ...useMyResource.prefetches(projectId)])- We could then write a test or lint rule checking that any file with
useCurrentProjectRole(also containsuseCurrentProjectRole.prefetch(
- We could then write a test or lint rule checking that any file with
- Make some kind of horrible higher-order component that produces both the loader and a component that has the prefetched data injected as props
- Rely more on
useLoaderDataas recommended by the RQ maintainer in his blog post React Query meets React Router- If instead of reading from the cache, we rely on pulling something out of
useLoaderDatato tell us whether it was prefetched - This might not work in cases where the current route doesn't have its own loader. I believe
useLoaderDatawill return the data from the nearest loader above it in the tree
- If instead of reading from the cache, we rely on pulling something out of
- Use
isStaleto test the query result rather than simply whether the data is present- That would make us subject to
staleTimerather thancacheTime. Not clear whether that really fixes anything.staleTimeis currently 10 seconds.
- That would make us subject to
- Nuclear option: don't use React Query for this. Just make the fetches like normal in loaders and use
useLoaderDatalike you're supposed to- One big downside here is that without RQ we don't get deduping of requests, so if the same request goes out at multiple levels, the calls will be duplicated. Maybe this isn't that important, and that's easier to see now that we have more of the console built out
- Another downside is that the typing on
useLoaderDatais fake — it returnsunknownand you're supposed to cast it to be the right thing. Unclear whether they're changing this any time soon, see Loader data generics remix-run/react-router#9854 - We would want to make that less error-prone somehow. One weird way to do it would be to require that
useLoaderData() as ...only ever be used in the same file as the loader itself, to avoid mixups where we're casting to the wrong loader's type
- Use or implement our own typesafe react router thing. Very interesting ideas in these projects (ordered from most weekly DLs to least)
- https://www.npmjs.com/package/react-router-typesafe-routes
- https://www.npmjs.com/package/typesafe-routes
- https://www.npmjs.com/package/typed-react-router
- https://www.npmjs.com/package/typesafe-router
Activity
david-crespo commentedon Jul 10, 2024
We haven't run into issues around this in a long time, so I'm going to close this. The upcoming
defineRouteAPI in RR v7 will probably help here, too.