我正在尝试实现一个loadMore
功能,该功能使用useQuery
的fetchMore
函数将项目附加到原始列表中。
const { data, fetchMore } = useQuery(GET_PODCAST_SERIES, {
variables: {
limit: 12,
offset: 0,
pathOrId: `${site}/podcast/${slug}`,
},
nextFetchPolicy: 'cache-first',
});
const length = data.PodcastSeriesQuery.podcastSeries.podcastEpisodes.length;
return <..>
...
<button onClick={() => {
fetchMore({
variables: { offset: length }
})
}}>load more</button>
</..>
查询看起来像这个
const GET_PODCAST_SERIES = gql`
query PodcastSeries($pathOrId: String, $limit: Int, $offset: Int) {
PodcastSeriesQuery(pathOrId: $pathOrId) {
podcastSeries(limit: $limit, offset: $offset) {
id
...
podcastEpisodes {
id
...
}
}
}
}
`;
缓存看起来像这个
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
PodcastSeriesQuery: {
keyArgs: ['pathOrId'],
merge(_, incoming) {
return incoming;
},
},
},
},
PodcastSeries: {
fields: {
podcastEpisodes: {
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
}),
问题是,每当我调用fetchMore
时,它都会发送两个网络请求,默认的一个总是被激发。例如
点击加载更多第一次
- network request 1 -> offset: 12, limit: 12, pathOrId: ...
- network request 2 -> offset: 0, limit: 12, pathOrId: ...
点击加载更多第二次
- network request 1 -> offset: 36 (even thought it should be 24, but it is still correct because the first click fetches twice making the data.list bigger), limit: 12, pathOrId: ...
- network request 2 -> offset: 0, limit: 12, ....
因此,默认查询始终被激发。。
我应该如何解决此问题?谢谢
这只是因为缓存不正确。我通过这个解决了这个问题
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
PodcastSeriesQuery: {
keyArgs: ['pathOrId'],
merge(existing, incoming) {
// before -> return incoming || existing;
return existing || incoming; // after
},
},
},
},
PodcastSeries: {
fields: {
podcastEpisodes: {
merge(existing = [], incoming) {
return [...existing, ...incoming];
},
},
},
},
},
}),