Avoid refetch on initial load
We have a main grid that is driven by a selected node in a navigation tree. Because
selectedNode
is persisted on the server and because the resources are slow/expensive, we load both asynchronously. However doing this means the grid is aborted/refetched (or refetched if the grid finishes first) when selectedNode
gets set so we're wondering if there's a good way to avoid triggering a refetch for that first load?
I was looking into initialData
or placeholderData
but I don't think either help me here. Tried finding the answer in Dominik's blog too https://tkdodo.eu/blog/effective-react-query-keysEffective React Query Keys
Learn how to structure React Query Keys effectively as your App grows
6 Replies
vicious-goldOP•2y ago
A thought I had was removing
selectedNodeId
from the queryKey
and invalidating myself...
But that feels wrong.dependent-tan•2y ago
Is selectedNode now needed to load the grid or not? I'm not really understanding the case
sensitive-blue•2y ago
I work with OP. The issue is we load data/nodes for a tree we use for navigation, and a grid. normally, clicking a tree node triggers the grid to load data. but in this case, the first time they load the server has remembered the user's last selection so the grid loads without waiting for the tree to load/first node selection.
so for the first load, the tree loads nodes and auto-selects the last selected node while the grid also loads using the last selected tree node. then, clicking different nodes in the tree triggers the grid to reload with that tree node as a param.
in most cases the tree always has to load first so it makes sense for the query key to use the selectedNode id. but in this we're unsure how to structure this so we don't load the grid twice (first using server-cached selectedNode id, then again when the tree loads and auto-selects the same node)
vicious-goldOP•2y ago
I think an easier way to state it is the grid is a dependent query except the first load
dependent-tan•2y ago
grid is a dependent query except the first loadthat's a bit problematic because queries are generally idempotent. They have the same dependenies, or they don't. So there is no real concept for Nth load. maybe you can set
enabled
by checking if grid has no data with queryClient.getQueryData
?vicious-goldOP•2y ago
enabled
would make them sequential fetches then which we were trying to avoid. That obviously simplifies it quite a bit but our client is quick to complain of slow load times
I’ll probably end up just using enabled
but I wanted to ask in case you had any good ideas