【问题标题】:Update cache after a mutation: Property 'names' does not exist on type '{ names: any; } | null'突变后更新缓存:类型'{名称:任何;属性'名称'不存在; } |空值'
【发布时间】:2020-07-31 07:42:41
【问题描述】:

使用带有钩子的 React 的 GraphQL 代码生成器,我正在尝试在突变后更新 Apollo 缓存,遵循 Apollo docs 中的示例:

  const [addName] = useAddNameMutation({
    update(cache, {data: {addName}}) {
      const {names} = cache.readQuery({query: GET_NAMES}); // Property 'names' does not exist on type '{ names: any; } | null'.
      cache.writeQuery({
        query: GET_NAMES,
        data: {names: names.concat([addName])},
      });
    },
  });

但是,我在解构查询变量上得到了Property 'names' does not exist on type '{ names: any; } | null'.

我做错了什么?

提前致谢。

【问题讨论】:

  • 你解决了吗?
  • 不,我将其视为“抽象过多”的错误

标签: graphql-codegen


【解决方案1】:

试试这个方法

const [addName] = useAddNameMutation({
    update(cache, {data: addName}) {
      cache.modify({
        fields: {
          names(existingNames = []) { // check if it is called 'names' in the Cache tab of Apollo Client dev tools in google chrome
            const newNameRef = cache.writeQuery({
              //query: GET_NAMES,
              query: GetNamesDocument, // assuming that your Query is called GetNames, and that in theory you would call it somewhere else like this: useGetNamesQuery()
              data: addName,
            })
            // return existingNames.concat(newNameRef) // if 'names' is a string, but I would think it's an array, then
            return [...existingNames, newNameRef]
          }
        }
      })
    },
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-10
    • 2019-12-10
    • 2020-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2017-10-21
    相关资源
    最近更新 更多