替换查询对象的my字段时,缓存数据可能会丢失

问题描述

这是我的代码

const NewVerificationCode = () => {
  const { loading,error,data = {},refetch } = useQuery(CONFIRMATION_CODE,{
    skip: true,onError: (err) => {},});
  console.log(loading,data);

  if (loading || error) {
    return <ErrorLoadingHandler {...{ loading,error }} />;
  }

  return (
    <form
      onSubmit={(e) => {
        refetch();
        e.preventDefault();
      }}
    >
      <div>
        <button type="submit" className="signUpbutton">
          {"Send the message again"}
        </button>
      </div>
    </form>
  );
};

const CONFIRMATION_CODE = gql`
  query {
    my {
      sendNewTokenForConfirmation
    }
  }
`;

我提出请求时会收到警告

替换查询对象的my字段时,缓存数据可能会丢失。

要解决此问题(这不是Apollo Client中的错误),请确保所有My类型的对象都具有ID,或者为Query.my>字段定义自定义合并功能,以便InMemoryCache可以安全地合并这些对象 现有:

    {"__typename":"My","getUser{"__typename":"User","email":"shakizriker0022@gmail.com"}}

incoming: {"__typename":"My","sendNewTokenForConfirmation":"SUCCESS"}

有关这些选项的更多信息,请参阅文档:

我关注了链接。

我阅读了文档,并意识到问题出在阿波罗客户端缓存(typePolicies)中。

但是我怎么解决这个我不知道的问题。

我应该在typePolicies中写些什么来摆脱警告?

解决方法

您可能需要返回Apollo的ID,以在缓存中唯一标识该对象。 我认为这个问题与您的相似: link

const CONFIRMATION_CODE = gql`
  query {
    my {
      id
      sendNewTokenForConfirmation
    }
  }
`;
,

每个对象都应返回 id、_id 或自定义 id 字段 (https://www.apollographql.com/docs/react/caching/cache-configuration),以便自动合并功能

const cache = new InMemoryCache({
  typePolicies: {
    Product: {
      keyFields: ["custom-id-field"],},});

(!)人们经常忘记缓存操作需要用于初始查询的相同变量(!)

突变样本(添加购买):

update(cache,{ data: NewPurchase } }) => {
  let productCache = cache.readQuery({
    query: productQuery,variables: {
      id: productId
    }
  })
 
  cache.writeQuery({
    query: productQuery,variables: { id: productId },data: {
      Product: {
        ...productCache.Product,purchases: productCache.Product.purchases.concat(NewPurchase)
      }
    }
  });
 };
}

(重要提示:每次购买还需要返回自己的个人 ID)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...