Fetch policies
jgoux opened this issue ยท 3 comments
Hello again ๐ ,
Description
Do you have/intend to propose a fetchPolicy option in the same spirit as https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-config-options-fetchPolicy ?
This is useful for controlling the UX. For example I often use a "cache-and-network" policy so a refetch of a query doesn't show a "loading" state again.
Hi @jgoux here's a breakdown of each policy and how we support it:
cache-first
If you provide a cache to new GraphQLClient({ cache })
this is the default behaviour
cache-and-network
The refetch
function provides this behaviour it will set loading: true
, but the old data will be still set until the fetch resolves.
In the example below I'm rendering both loading and data - best of both worlds, you could render the stale data but also have a loading indicator. Or if you wish, ignore the loading state if data
is truthy.
I've also implemented an effect to call onMount, that checks if the query result came from the cache to refetch it.
function MyComponent() {
const { loading, error, data, cacheHit, refetch } = useQuery(QUERY)
useEffect(() => {
if (cacheHit) {
refetch()
}
}, [])
return (
{error && <div>Error!</div>}
{loading && <div>loading</div>}
{data && <div>{data}</div>}
)
}
network-only
useQuery(QUERY, { skipCache: true })
- This is useful for particular render cycles you can conditionally set skipCache.
cache-only
We don't support this, I'm not sure there are any valid use-cases of this.
no-cache
useQuery(QUERY, { useCache: false })
@bmullan91 - Could we take what you've written there and drop it in the README
under a guide heading of Fetch policies
?
This is now documented as part of the Migrating from Apollo
guide.