我正在学习 apollo 和 graphQL,并且有一个简单的应用程序,它显示一个数据列表,带有一个添加到数组的 fetchMore 函数。
我想删除 updateQuery,因为它已被弃用并使用新的字段策略合并功能。当前缓存设置和 updateQuery 如下所示:
const cache = new InMemoryCache({
typePolicies: {
client_client: {
fields: {
// add local only value to clients
isEdited: {
read(value = false) {
// when writing the new value return new value or false as default
return value;
},
}
}
}
}
});
const onFetchMore = () => {
fetchMore({
variables: {
offset: page
},
updateQuery: (previousResult, { fetchMoreResult, queryVariables }) => {
return {
...previousResult,
client_client: [
...previousResult.client_client,
...fetchMoreResult.client_client,
],
};
},
});
}
但是,我似乎无法让它在 apollo 客户端 v3 的缓存中作为合并函数工作。我尝试在许多不同的地方添加合并,但它似乎总是会破坏应用程序。任何有关如何做到这一点的帮助将不胜感激。
最佳答案
根据文档,在 typePolicies
中定义字段策略InMemoryCache
中提供的选项构造函数:
const cache = new InMemoryCache({ typePolicies: { Query: { fields: { feed: { // Don't cache separate results based on // any of this field's arguments. keyArgs: false, // Concatenate the incoming list items with // the existing list items. merge(existing = [], incoming) { return [...existing, ...incoming]; }, } } } } })
然后你只需通过
offset
和 limit
到初始查询:const { loading, data, fetchMore } = useQuery(GET_ITEMS, { variables: { offset: 0, limit: 10 }, });
和
fetchMore
获得下一次迭代:fetchMore({ variables: { offset: 10, limit: 10 }, });
在此处查看文档:https://www.apollographql.com/docs/react/pagination/core-api/
关于graphql - 如何将 apollo 客户端 fetchMore updateQuery 转换为 apollo 缓存合并功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63523293/