突变后更新阿波罗缓存时发生不变违规错误

时间:2019-07-30 10:02:32

标签: apollo react-apollo

在此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({})   ...

1 个答案:

答案 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