Fetch Policies
Fetch Policies
Defines whether a query gets its data from the cache
or from the API
.
Decision of getting the most recent data from the server or getting a faster response from the cache.
Errors are not cached
By default, the error policy treats any GraphQL Errors as network errors and ends the request chain. It doesn't save any data in the cache.
You can set this policy manually as below:
const MY_QUERY = gql` query WillFail { badField goodField } `; function ShowingSomeErrors() { const { loading, error, data } = useQuery(MY_QUERY, { errorPolicy: 'all' }); if (loading) return <span>loading...</span> return ( <div> <h2>Good: {data.goodField}</h2> <pre>Bad: {error.graphQLErrors.map(({ message }, i) => ( <span key={i}>{message}</span> ))} </pre> </div> ); }
cache-first
Default fetch policy.
Favors quick response times for queries over getting the most up-to-date data.
Steps:
- query for data
- If cache is present:
- Request data is returned
- If cache is not present:
- Apollo server makes a network request to API
- API responds with requested data
- Apollo updates the cache
- Requested data is returned
cache-and-network
Little more emphasis than cache-first
on keeping the cache up to date.
Could be a good fetch policy if you have data that is changing frequently and queries are returning out-of-date information.
Steps:
- Query is ran, Apollo checks the cache
- If cache has the data:
- return the cached data
- Whether cache has the requested data or not, it executes the query to the API to get the up-to-date data
- Apollo updates the cache with new data from API
- Returns the updated data
network-only
Prioritizes up-to-date data over response speed.
It never returns outdated information from the cache
.
Steps:
- Apollo makes network request without checking the cache
- Server responds with data and cache is updated
- Data is returned
no-cache
no-cache
is similar to network-only
but skips the step to update the cache.
Steps:
- Apollo makes network request without checking cache
- Server responds and the data is returned without updating the cache
cache-only
Opposite of no-cache
.
Avoids making any network request.
- If the data is not available in the
cache
, request will throw and error.
Useful if you want to display consistent information to the user.
- Will completely ignore any server-side changes.