在此article删除项目后,我尝试更新我的列表
但是会出现不变违规错误。
我的突变:
const deleteFn = useMutation<FeaturedPlaylistGroupDelete, FeaturedPlaylistGroupDeleteVariables>(deleteQuery, {
update: (cache, mutationResult) => {
console.log('mutationResult', mutationResult)
const data = cache.readQuery({ query: featuredPlaylistsGroupsQuery })
console.log('cache', cache)
console.log('cacheData', data)
cache.writeQuery({
query: featuredPlaylistsGroupsQuery,
data: data.filter((item) => item.id !== mutationResult.data.featuredPlaylistGroupDelete.id),
})
},
})
featuredPlaylistsGroupsQuery:
export const featuredPlaylistsGroupsQuery = gql`
query FeaturedPlaylistGroups(
$active: Boolean
$noCategory: Boolean
$dateFrom: String
$dateTo: String
$title: String
$regions: [String!]
$categories: [String!]
) {
featuredPlaylistGroups(
active: $active
noCategory: $noCategory
dateFrom: $dateFrom
dateTo: $dateTo
regions: $regions
title: $title
categories: $categories
) {
active
category {
title
}
datetime
id
region
title
}
}
`
deleteQuery:
const deleteQuery = gql`
mutation FeaturedPlaylistGroupDelete($id: String!) {
featuredPlaylistGroupDelete(id: $id) {
active
categoryId
category {
title
}
datetime
id
region
title
}
}
`
错误:
不变违反:找不到字段 对象{上的FeaturedPlaylistGroups({}) ...
答案 0 :(得分:1)
使用readQuery
时,返回的内容是该查询的响应data
部分中返回的内容。这是总是的对象。因此,对于类似
query {
foo
bar
}
您得到一个类似
的对象{
"foo": "FOO",
"bar": "BAR"
}
当您使用readQuery
调用featuredPlaylistsGroupsQuery
时,将获得一个具有名为featuredPlaylistGroups
的单个属性的对象。因此,您的代码应更像:
const cached = cache.readQuery({ query: featuredPlaylistsGroupsQuery })
const featuredPlaylistGroups = cached.featuredPlaylistGroups.filter(item => {
return item.id !== mutationResult.data.featuredPlaylistGroupDelete.id
})
const data = {
...cached,
featuredPlaylistGroups,
}
cache.writeQuery({
query: featuredPlaylistsGroupsQuery,
data: data,
})
但是,由于featuredPlaylistsGroupsQuery
包含许多变量,因此仍然无法使用。我们需要这些变量以便从缓存中读取和写入数据,因为已被查询的变量的每种组合都分别存储在缓存中。因此,您要么需要跟踪使用的变量,然后对所有使用的组合调用readQuery / writeQuery,要么使用类似apollo-link-watched-mutation