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
    }
  });
}