Apollo GraphQL客户端:如何将乐观响应与真实响应区分为watchQuery

时间:2018-05-16 07:44:33

标签: apollo graphql-js apollo-client

问题是关于突变,乐观反应和watchQuery的相互作用。

我有一个突变" myMutation"它有一个" optimisticResponse"和实施的#34;更新"功能

每次我进行突变查询"更新"函数被调用两次,第一次使用乐观响应数据,第二次使用实际数据。一切都很好,所有内容都在文档中描述。

进入我的"更新"功能我修改" myQuery"通过使用readQuery / writeQuery方法缓存数据。

每次我修改" myQuery"缓存数据调用watchQuery(基于" myQuery")订阅。一切都很好,所有内容都在文档中描述。

但问题是我无法区分我的watchQuery是否收到乐观的响应数据或真实的响应数据。这对我来说至关重要,因为反应必须不同,因为有价值的数据部分只能由服务器提供。 当我收到乐观的回复时,我应该展示一个具有特殊风格的GUI元素,我应该禁止与它进行任何交互,直到我收到真实的回复。

不幸的是,我无法解决这个问题。乍看之下,乐观和真实反应之间没有区别。我已经搜索了很多东西,并没有找到解决方案。我唯一的想法是在我的GraphQL数据中添加一个特殊字段,该字段将显示是否从服务器接收到响应。但它看起来很难看,闻起来很糟糕。我相信,必须有一个简单的正确方法来克服这个问题。

1 个答案:

答案 0 :(得分:1)

也许有一种更简单的方法,或者将来会有一种方式,但这就是我所知道的。

optimisticResponse中的数据仅在第一次更新调用期间提供。在这里,您可以向您的更新函数标记它正在处理乐观数据。您可以在那里放置任何数据。我把isOptimistic: true,

为了解决watchQuery问题,我建议您使用apollo-link-state将仅客户端字段添加到数据模型的区域,其中应该知道显示的乐观upsert 。不要在您的变异查询中包含isOptimistic,这样您就可以从服务器而不是乐观响应中知道它,如果不成立,则强制它为假。见这个例子:

const SUBMIT_COMMENT_MUTATION = gql`
  mutation submitComment($repoFullName: String!, $commentContent: String!) {
    submitComment(
      repoFullName: $repoFullName
      commentContent: $commentContent
    ) {
      postedBy {
        login
        html_url
      }
      createdAt
      content
    }
  }
`;

const CommentsPageWithMutations = ({ currentUser }) => (
  <Mutation mutation={SUBMIT_COMMENT_MUTATION}>
    {mutate => (
      <CommentsPage
        submit={(repoFullName, commentContent) =>
          mutate({
            variables: { repoFullName, commentContent },
            optimisticResponse: {
              __typename: "Mutation",
              submitComment: {
                __typename: "Comment",
                postedBy: currentUser,
                createdAt: new Date(),
                content: commentContent,
                isOptimistic: true // Only provided to update on the optimistic call
              }
            },
            update: (proxy, { data: { submitComment } }) => {
              // Make sure CommentAppQuery includes isOptimistic for each comment added by apollo-link-state
              // submitComment.isOptimistic will be undefined here if it's from the server
              const newComment = { ...submitComment, isOptimistic: submitCommit.isOptimistic ? true : false }
              // Read the data from our cache for this query.
              const data = proxy.readQuery({ query: CommentAppQuery });
              // Add our comment from the mutation to the end.
              data.comments.push(newComment);
              // Write our data back to the cache.
              proxy.writeQuery({ query: CommentAppQuery, data });
            }
          })
        }
      />
    )}
  </Mutation>
);

请参阅https://www.apollographql.com/docs/link/links/state.html

相关问题