React Client – Manually Add Query to Cache before Fetching

Hi there!

Question
Is there some option to add “active Queries” to Apollo’s cache without actually running a network request?

What I want to do

  • I am prefetching a list of “Items” with useQuery “GetItemList” on initial page load. The response already contains all the fields for each of individual items.
  • Some components in the application later use another useQuery “GetItem” which fetches an individual Item with exactly the same fields the GetItemList fetched earlier.
  • All the data for Item:id is already in Apollo’s cache at that point.
  • What I would like to happen, is that instead of shooting another request to the server, the data should be just taken from the cache.

What I tried so far

  • Using a for loop to individually write to apollo’s cache using client.writeQuery({query: ItemQuery, data: { item}}) (works)
  • However, useQuery(ItemQuery) triggers the network request anyways with the “cache-first” policy (I believe, that ItemQuery being not registered among “Active Queries” in Apollo’s Dev Tools might have something todo with it)
  • If I call useQuery(ItemQuery) with “cache-only” is returns undefined, even though I can see that the specific item is present in the cache.

Any ideas how I can resolve this?

[SOLVED]

After reading through other forum entries, I found a solution: useQuery makes request instead taking data from cache - #2 by StephenBarlow