【发布时间】:2021-05-27 05:01:22
【问题描述】:
我有一个简单的突变editPerson。它会更改id 指定的人的姓名和/或描述。
我使用这个小 sn-p 从 React 组件中调用 mutator:
function useEditPerson(variables) {
const gqlClient = useGQLClient();
const personFragment = gql`fragment useEditPerson__person on Person {
id
name
description
}`;
return useMutation(gql`
${personFragment}
mutation editPerson($id: ID!, $description: String, $name: String) {
editPerson(id: $id, description: $description, name: $name) {
...useEditPerson__person
}
}
`, {
variables,
optimisticResponse: vars => {
const person = gqlClient.readFragment({
id: vars.id,
fragment: personFragment,
});
return {
editPerson: {
__typename: "Person",
description: "",
name: "",
...person,
...vars,
},
};
},
});
}
除非指定人员的name 或description 尚未被查询且缓存中不存在,否则此方法运行良好;在这种情况下,person 是 null。这是readFragment 所期望的 - 任何不完整的片段都会这样做。
问题是我真的需要这些数据来避免不变的错误 - 如果它们不在缓存中,我完全可以使用空字符串作为默认值,这些值无论如何都不会显示在 UI 中的任何位置。
有没有办法从缓存中读取部分片段?有没有更好的方法来获取乐观响应的数据?
【问题讨论】:
-
hmmm,
console.log(并显示)所有这些person,vars,variables,准备好乐观(待返回)对象???为什么是id: variables.id,而不是id: vars.id? -
@xadm ha - 这是一个很好的收获。这是我的代码的超级配对版本(为了 Stack Overflow)。我的实际代码使用
vars.id
标签: graphql apollo apollo-client react-apollo