Closed valerybugakov closed 1 year ago
Now for how to implement this, I also have a few ideas based on the framework:
The most naive version would be to manually run a query
in the data loader. The issue here is that the data loader is not a hook and is run on discrete actions (e.g. on a link being clicked (or even hovered) the data loader might be run). Because of this, it can't use React hooks so for any code inside it, it would need imperative APIs. In the Apollo case, it would mean that queries are done via ApolloClient#query()
instead of useQuery
. This, however, comes with some concerns:
useQuery
call and make sure to properly support nesting (think e.g. of the case where we have a list and want to support loading the next page)This obviously needs more exploration but I’m thinking of being able to do something like this:
const QUERY = gql`query { ...}`;
export function loader() {
return {
queryReference: preloadQuery(QUERY, {params: {id}}),
}
}
function App() {
const {queryReference} = useLoaderData();
const data = usePreloadedQuery(data.QUERY, {params: {id}}, queryReference)
}
The idea here is to add a preloadQuery
function that can do the initial query for us (using ApolloClient#query
) and then have it pass some data to a new hook usePreloadedQuery
that maybe even use a useSuspendedQuery
but also does some book-keeping to make sure we don't start a new query if the query was already preloaded. We could do this by multiple means but one simple idea to get started is to hijack the network
layer (so when we encounter a fetch()
for this query, we simply return the same Promise that we created in the preloadQuery
above?
Apollo
times. Which comes at the expense of a proper cache (but we'd get the cache from setting up react-router data-loaders correctly). This way everything is in our control but it's likely we spent a lot of time maintaining this approach.We ended up implementing a prototype that uses Apollo: https://sourcegraph.slack.com/archives/C04KDBTLG5P/p1673966112312489
Context
Review options available to us considering our current web application stack. Document possible approaches with pros and cons for each so we can discuss them on the next project sync and document our decision with alternatives review.