Dol*_*ios 5 apollo graphql-js apollo-client
问题是关于突变,乐观响应和watchQuery的交互.
我有一个突变"myMutation",它有一个"optimisticResponse"和一个实现的"更新"功能.
每次我进行变异查询时,"update"函数被调用两次,第一次使用乐观响应数据,第二次使用实际数据.一切都很好,所有这些都在文档中描述.
在我的"更新"功能中,我通过使用readQuery/writeQuery方法修改"myQuery"缓存数据.
每次我修改"myQuery"缓存数据时,都会调用watchQuery(基于"myQuery")订阅.一切都很好,所有这些都在文档中描述.
但问题是我无法区分我的watchQuery是否收到乐观的响应数据或真实的响应数据.这对我来说至关重要,因为反应必须不同,因为有价值的数据部分只能由服务器提供.当我收到乐观的响应时,我应该显示一个具有特殊风格的GUI元素,我应该禁止与它进行任何交互,直到我收到真实的响应.
不幸的是,我无法解决这个问题.乍看之下,乐观和真实反应之间没有区别.我已经google了很多,并没有找到解决方案.我唯一的想法是在我的GraphQL数据中添加一个特殊字段,该字段将显示是否从服务器收到响应.但它看起来很难看,闻起来很糟糕.我相信,必须有一个简单的正确方法来克服这个问题.
小智 6
也许有一种更简单的方法,或者将来会有一种方法,但这是我所知道的。
optimisticResponse仅在第一次调用更新期间提供数据。您可以在此处向更新函数标记它正在处理乐观数据。您可以在那里放置任何您想要的数据。我放isOptimistic: true,。
为了解决这个watchQuery问题,我建议您将apollo-link-state一个或多个客户端专用字段添加到数据模型中应该显示乐观更新插入的区域。不要包含isOptimistic在您的突变查询中,这样您就知道它来自服务器而不是乐观响应,如果不正确,则强制其为 false。看这个例子:
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>
);
Run Code Online (Sandbox Code Playgroud)
请参阅https://www.apollographql.com/docs/link/links/state.html。
| 归档时间: |
|
| 查看次数: |
776 次 |
| 最近记录: |