更改后更新缓存:类型 '{ names: any; } | null' 上不存在属性'names'



使用带有钩子的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'.

我做错了什么?

提前谢谢。

尝试这种方式

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