Cache-only Fetch Policy Use Case

I have noticed that the docs say that the cache-only fetchPolicy throws an error if the data is not in the cache, but it doesn’t actually. It just returns null for data, so I am wondering if the Docs are outdated.

The reason why I ask is because I have a use case for cache-only but it relies on no error being thrown if the data is not found in the cache. My use case is detailed below.

I have two components that hit the same query but with different fields. Both components are rendered on page load. The first query gets field1 and field2 and the second query only gets field1. Because these two requests happen around the same time they always trigger two separate requests even though the first query by itself would populate the cache with everything needed for both queries.

My solution to this problem was to make the second query cache-only so that it waits until the first query populates the cache and doesn’t trigger a second request.

Is this an appropriate use of the cache-only fetch policy? There isn’t a lot of information about it in the docs, except that it should throw an error if the data isn’t found in the cache (which would be problematic in my use case).

2 Likes

Why don’t you put simple logic in the parent component to only render the 2nd component when the 1st component is loaded?

const Parent: React.FC<{}> = () => {
  const [firstLoaded, setFirstLoaded] = React.useState(false);

  return (
    <First onLoaded={() => { setFirstLoaded(true) }} />
    {firstLoaded && <Second />}
  )
}

The component hierarchy in my case doesn’t allow it because the two components are distant relatives. A simplified version of the Hierarchy I am working with is below.

App >
  MainNav (Query 2)
  Route >
    SideBar (Query 1) 
    Content

Sorry, juggling on my end, and didn’t get a notification for this for whatever reason.

Maybe use context? Personally, I’d try to use React to handle this, because it seems mostly like an application/business logic problem, rather than a networking problem.

I’d dig around and see if there’s a React tool for this job, and if not I’d think that it might actually be useful to check if there’s some kind of query aggregation middleware for this, where it can “combine” multiple queries into one under the hood if they’re both fired during a window of say, 100ms.