Fetchmore is not using cache
See original GitHub issueWhen using pagination and doing a fetchMore request the cache is not used to read data,
While data is already in the cache and having implementations for ‘read’ and ‘merge’ field policies, it looks like the ‘fetchMore’ is not using the typePolicy ‘read’ function and direcly does a network request. Also the fetchPolicy is not used, for example if you set it to ‘cache-only’, fetchmore is doing network requests.
It’s kinda like the example from the documentation:
const FeedData({ type = "PUBLIC" }) {
const [limit, setLimit] = useState(10);
const { loading, data, fetchMore } = useQuery(FEED_QUERY, {
variables: {
type: type.toUpperCase(),
offset: 0,
limit,
},
});
if (loading) return <Loading/>;
return (
<Feed
entries={data.feed || []}
onLoadMore={() => {
const currentLength = data.feed.length;
fetchMore({
variables: {
offset: currentLength,
limit: 10,
},
}).then(fetchMoreResult => {
// Update variables.limit for the original query to include
// the newly added feed items.
setLimit(currentLength + fetchMoreResult.data.feed.length);
});
}
/>
);
}
Sometimes if you scroll 500 items with a continuous scroll implementation, which loads 500 items in the cache, the component gets unmounted, and mounts again, you do not want all the 500 items to show at once because the rendering could be slow. I want to just to show the initial 10 items, and “fetchMore” from the cache or network (if it’s not in the cache), while you scroll for more items. so in the typePolicy I have something like:
const policy = {
Query: {
fields: {
feed: {
keyArgs: ['type'],
merge: {
// merge from offsetLimitPagination
},
read(existing, { args }) {
if (!args || !existing || !(args.limit >= 0)) {
return existing;
}
if (existing.length >= args.limit + (args.offset ?? 0)) {
return existing.slice(args.offset ?? 0, args.limit ?? existing.length);
}
// not enough data
},
},
},
},
};
But ‘read’ is never called when using fetchmore and always does a network call even though all the data is in the cache for the first 500 items.
Apollo version 3.3
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:11 (4 by maintainers)
@awlevin I had also this problem. My current solution is to generate some typePolicies based on the schema. New arguments to fields are generated in the type policies automatically. But offcourse, a negated keyArgs would be nice. Something like excludedKeysArgs. Then the field key should be constructed with argnames included and sorted by argname.
@robertsmit If you have some way to detect the event of navigating back to the component, you should be able to call
setLimit(10)
to reset the window.The
fetchMore
method sends a separate request that always has a fetch policy ofno-cache
, which is why it doesn’t try to read from the cache first.