也许有更简单的方法,或者将来会有,但这是我所知道的。
optimisticResponse 中的数据仅在第一次调用更新期间提供。您可以在此处向更新函数标记它正在处理乐观数据。你可以把你想要的任何数据放在那里。我把isOptimistic: true,.
为了处理watchQuery 问题,我建议您使用apollo-link-state 将一个或多个仅限客户端的字段添加到您的数据模型中应该显示乐观向上插入的区域。不要在你的突变查询中包含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。