如何解决对相同 __typename 数据的不同查询在 Apollo Graphql 上从缓存返回 undefined
我对 Apollo 和 Graphql 相当陌生,我完全不知道我做错了什么。我会尝试用一些简化的代码来解释我的问题,但如果我遗漏了一些信息,请告诉我,我会更新它。
我有一个 Apollo 客户端实例,它使用我无法修改的外部(Directus CMS)graphql API。 问题是我正在查询带有偏移和限制变量的分页(无限滚动)帖子,并且返回的数据是正确的。我正在使用以下 typePolicy 来合并 inMemoryCache 中的结果数组。此代码来自 Apollo Docs 中的示例:
posts {
const merged = existing ? existing.slice(0) : [];
const postIdToIndex = Object.create(null);
if (existing) {
existing.forEach((post,index) => {
postIdToIndex[readField("id",post)] = index;
});
}
incoming.forEach((post) => {
const id = readField("id",post);
const index = postIdToIndex[id];
if (typeof index === "number") {
// Merge the new post data with the existing post data.
merged[index] = mergeObjects(merged[index],post);
} else {
// First time we've seen this post in this array.
postIdToIndex[id] = merged.length;
merged.push(post);
}
});
return merged;
}
这是我查询的简化版本:
query($offset: Int $limit: Int) {
posts(limit: $limit offset: $offset) {
id
name
}
}
使用此合并功能和查询,我可以正确地进行分页并且所有内容都正确加载。但是,当我尝试查询单个 post 实例时,该实例还使用以下查询从中查询其他字段:
query($offset: Int $limit: Int $post_id: Int) {
posts(filter:{id:{_eq: $post_id}}) {
id
name
other_data
}
}
这在使用 useQuery() 时不断返回 undefined 虽然我可以看到这是通过我的合并功能和使用 mergeObjects() 函数合并对象。如果我在此查询中使用 no-cache 的 fetchPolicy,数据将正确返回,因此它与缓存有关。
我希望有人能引导我走向正确的方向,以便我解决这个问题。
先谢谢大家!!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。