首页 > 解决方案 > 如何将查询与 apollo 的 refetchQuery 匹配

问题描述

我的基本问题是查询的变量是否需要准确才能使 refetchQueries 工作。或者你可以给它一个变量子集,它会匹配类似的查询。

考虑以下 ....

  <Query<NotesQuery, NotesQueryVariables>
      query={notesQuery}
      variables={{
        input: {
          notebookId: notebookContext.id,
          first: 20
        }
      }}
    >
</Query>

和以下突变:

    client
      .mutate<NoteCreateOrUpdateMutation, NoteCreateOrUpdateMutationVariables>({
        mutation: noteCreateOrUpdateMutation,
        variables: {
          input: {
            noteId: note ? note.id : undefined,
            subjectIds: noteSubjects,
            notebookId: notebookContext.id,
            authorId: userContext.id,
            content: noteContent,
            context: noteCaption,
          }
        },
        refetchQueries: [
          {
            query: notesQuery,
            variables: { input: { notebookId: notebookContext.id } } as NotesQueryVariables
          }
        ]
      })

当我执行该突变时,它不会使用分页重新获取注释查询

如果我添加first: 20参数 - 它可以工作。

我希望它清除与给定参数匹配的所有 noteQueries。那可能吗?

标签: graphqlapolloapollo-client

解决方案


我相信您会想要在和的定义中添加@connection指令。您没有发布这些内容,所以很遗憾,我无法准确地向您展示您的用例会是什么样子。gqlnotesQuerymeasurementsQuery

无论如何,该@connection指令将允许 Apollo 匹配notebookId例如,而忽略first.

不幸的是,您已将所有输入捆绑到 objectinput中,我不知道您将如何仅notebookId使用过滤器进行选择。假设您的gql定义看起来像这样notesQuery

const notesQuery = gql`
  query notes($input: InputType!) {
    notes(input: $input) @connection(key: "notes", filter: ["input['notebookId']"]) {
      id
      ...
    }
  }
`;

^^^ 不幸的是,由于apollo-utilities/lib/storeUtils.js->getStoreKeyName()函数的工作方式,这不起作用。它只会忽略上述尝试获得比 arg 名称更好的分辨率,即不能超越input. 过滤器数组中与 arg 名称不匹配的任何字符串都会被忽略。

看起来你必须修改你的架构。

更多信息请访问:https ://www.apollographql.com/docs/react/features/pagination.html#connection-directive


推荐阅读