2

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

  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'.了解构查询变量。

我究竟做错了什么?

提前致谢。

4

1 回答 1

0

试试这个方法

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]
          }
        }
      })
    },
  });
于 2021-04-08T05:45:19.860 回答