gpt4 book ai didi

apollo-client - Apollo Client 中的乐观响应与更新?

转载 作者:行者123 更新时间:2023-12-04 05:11:28 29 4
gpt4 key购买 nike

我想在突变后使用乐观 UI 更新:https://www.apollographql.com/docs/react/basics/mutations.html

我对“乐观响应”和“更新”之间的关系感到困惑。

这里使用了乐观响应:

    const CommentPageWithData = graphql(submitComment, {
props: ({ ownProps, mutate }) => ({
submit: ({ repoFullName, commentContent }) => mutate({
variables: { repoFullName, commentContent },

optimisticResponse: {
__typename: 'Mutation',
submitComment: {
__typename: 'Comment',
// Note that we can access the props of the container at `ownProps` if we
// need that information to compute the optimistic response
postedBy: ownProps.currentUser,
createdAt: +new Date,
content: commentContent,
},
},
}),
}),
})(CommentPage);

是否仅使用此更新商店?

然后文档说这用于更新缓存:
    const text = 'Hello, world!';

client.mutate({
mutation: TodoCreateMutation,
variables: {
text,
},
update: (proxy, { data: { createTodo } }) => {
// Read the data from our cache for this query.
const data = proxy.readQuery({ query: TodoAppQuery });

// Add our todo from the mutation to the end.
data.todos.push(createTodo);

// Write our data back to the cache.
proxy.writeQuery({ query: TodoAppQuery, data });
},
});

这是我在不使用optimisticResponse 函数的情况下成功更新UI 的方法。

两者有什么区别?你应该同时使用两者还是只使用一个?

最佳答案

为了扩展其他两个答案,区别在于您正在“更新”的内容是否已经存在于缓存中。

根据 docs , 如果您正在更新现有项目,例如编辑待办事项的标题,您只需要 optimisticResponse .为什么?因为缓存包含节点,您只需要告诉它新节点发生了新的事情,这会立即反射(reflect)在 UI 上。

optimisticResponse just provides an 'immediate' result data from a mutation.



现在我们有第二种情况,您想向列表中添加一个新的 Todo 项。首先,缓存需要知道创建了一个新项目。只要您提供 update归因于突变,您正在控制缓存的状态。

update takes place of refetchQueries, which means you are in control of the cache state.



update您可以访问缓存并专门修改/附加您需要的节点,而不是重新获取整个数据层次结构。但是,您仍在等待 Mutation 完成。如果您提供 update旁边 optimisticResponse ,您正在提供一个即时的假设响应,并将其提供给您的个人 update函数,然后立即更新缓存。

这两者在方案二中配对的原因是您完全绕过了服务器响应。如果您只是给出“立即”响应,Apollo 仍处于等待服务器更新缓存的模式。 update让您也可以劫持它,并在客户端进行。

Final Note: you are assuming the server is always responding without errors. Error handling elsewhere will still work, but you might get into UI inconsistencies if you are frequently catching errors (say isLoggedIn scenarios) so def make sure that the queries you 'fast track' are typically healthy.

关于apollo-client - Apollo Client 中的乐观响应与更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49186523/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com