如何解决Apollo Client - 从缓存中读取
React + Apollo 客户端应用程序。我正在尝试使用
const [products,setProducts] = useState({})
React.useEffect(() => {
const fetchData = async () => {
const result = await fetch('http://127.0.0.1:5000/listProducts')
// console log here to determine how to set products
console.log(result)
setProducts(result)
}
fetchData()
},[])
React.useEffect(() => {
if (!!products) {
// here you Could access products!
}
},[products])
if (!products) return null
return products.map((product) => (
<>
<h1>{products.ProductName}</h1>
<h1>{products.ProductDescription}</h1>
</>
))
从我的缓存中读取,但无法读取缓存的字段。
这是一个纲要:
组件 readQuery
调用 SinglePost
执行我的 useQuery
查询并缓存结果。 GET_POST
查询返回类型 GET_POST
。一切正常,开发工具显示 Post!
包含一个名为 getPost 的字段,其中包含该帖子。
ROOT_QUERY
const { loading,data } = useQuery(GET_POST,{
variables: {
postID,}
});
有一个子组件 SinglePost
,用于在点击时删除评论。它调用 DeleteButton
并删除评论。 useMutation
查询返回类型 DELETE_COMMENT
。
Comment!
Post 有一个评论数组,现在我需要在缓存中更新它的数组并删除已删除的评论。我在 const [deleteComment] = useMutation(DELETE_COMMENT,commentID,},});
突变中使用 update
函数来获取缓存对象并使用 deleteComment
从中获取 getPost 字段,但它返回 null ,即使它在开发工具中。
readQuery
我怀疑当通过返回 update(cache,result) {
const cacheData = cache.readQuery({
query: GET_POST,});
// code that doesn't run because cacheData is null
}
类型的变异对帖子进行变异时,它成功读取了 getPost 字段,但是当变异查询返回 Post
类型时,它无法读取getPost 在它的变异钩子中......因为没有对 Comment
类型的引用?
目前我使用 Post
作为解决方法。我不喜欢对服务器进行额外的调用,但我的大脑无法弄清楚这一点。任何帮助表示赞赏。
解决方法
糟糕,没有变量被传递给查询。
update(cache,result) {
const cacheData = cache.readQuery({
query: GET_POST,variables: {
postID
}
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。