【问题标题】:Apollo Client 3: how to cache a mutation result into a nested collection? (collection within a collection)Apollo Client 3:如何将突变结果缓存到嵌套集合中? (集合中的集合)
【发布时间】:2022-10-16 01:46:12
【问题描述】:

在我的 Apollo Client 3 应用程序中,我正在做一个突变,并希望将结果缓存到一个集合中,该集合嵌套在集合的一个项目中。

具体来说,我在 cmets 列表、帖子中的每个列表、帖子列表中的每个帖子中创建了一个 comment。我的应用程序的数据层次结构如下所示:

user 1
    profile 1
        post 1
            comment 1.1
            comment 1.2
        post 2
            comment 2.1
            comment 2.2
            < write mutation result here >
        post 3
            comment 3.1
            comment 3.2
            comment 3.3
        ...

在这种情况下,我如何最好地将创建的评论缓存到其父帖子的评论集合中?我正在查看 useMutation 钩子的 updatemodify 配置,但不太确定。

对于其他上下文,这里是对应于上述数据层次结构的查询:

query getUserPosts($userParams: GetUserParams!$postsPaginationParams: CursorPaginationParams!) {
  user(params: $userParams) {
    id
    profile {
      id
      # ...
      ownedPosts(pagination: $postsPaginationParams) {
        items {
          id
          # ...
          featuredComments {
            id
            primaryText
            creationTimestamp
            owner {
              id
              name
            }
          }
        }
        pagination {
          # ...
        }
      }
    }
  }
}

这是我的突变:

input CreateCommentParams {
  ownerId: String!
  postId: String!
  primaryText: String!
}

mutation createComment($params: CreateCommentParams!) {
  createComment(params: $params) {
    id
    owner {
      id
      name
    }
    primaryText
    creationTimestamp
  }
}

到目前为止,useMutation 是这样的:

useMutation(CREATE_COMMENT_MUTATION, {
  // ...
  update: (cache, { data }) => {
    if (data) {
      const cacheId = cache.identify(data.createComment);
      cache.modify({
        fields: {
          // ...how to update the comments array of the specific post? 
        }
      })
    }
  },
})

【问题讨论】:

    标签: graphql apollo-client


    【解决方案1】:

    您需要找到您正在更新的帖子并更新其 featuresComments 字段,如下所示:

    useMutation(CREATE_COMMENT_MUTATION, {
      // ...
      update: (cache, { data }) => {
        cache.modify({
          id: cache.identify({
            __typename: 'Post', // Assuming your this is the _typename of your Post type in your schema
            id: postId,
          }),
          fields: {
            featuredComments: (previous, { toReference }) => [...previous, toReference(data.createComment)]
          },
        }),
      }),
    })
    

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2011-05-30
      • 1970-01-01
      • 2012-12-08
      • 2011-04-07
      • 1970-01-01
      • 2015-12-07
      • 2022-01-09
      • 1970-01-01
      相关资源
      最近更新 更多