Skip to content

Ensure correct loader prefetches for each page #1703

Closed as not planned
Closed as not planned

Description

@david-crespo

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.

console/app/routes.tsx

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 direct usePrefetchedApiQuery calls 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 useCurrentProjectRole in 6606d78, we could make it so the hook has a prefetches function 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 contains useCurrentProjectRole.prefetch(
  • 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 useLoaderData as 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 useLoaderData to tell us whether it was prefetched
    • This might not work in cases where the current route doesn't have its own loader. I believe useLoaderData will return the data from the nearest loader above it in the tree
  • Use isStale to test the query result rather than simply whether the data is present
    • That would make us subject to staleTime rather than cacheTime. Not clear whether that really fixes anything. staleTime is currently 10 seconds.
  • Nuclear option: don't use React Query for this. Just make the fetches like normal in loaders and use useLoaderData like 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 useLoaderData is fake — it returns unknown and 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)

Activity

  1. david-crespo commented on Jul 10, 2024

    @david-crespo
    CollaboratorAuthor

    We haven't run into issues around this in a long time, so I'm going to close this. The upcoming defineRoute API in RR v7 will probably help here, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions