Apollo 可以从缓存中读取部分片段吗?

问题描述

我有一个简单的突变 editPerson。它会更改由 id 指定的人员的姓名和/或描述。

我使用这个小片段从 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,},};
        },});
}

除非指定人员的 namedescription 尚未被查询且不存在于缓存中,否则此方法运行良好;在这种情况下,personnull。这是 readFragment 的预期 - 任何不完整的片段都会这样做。

问题是我真的需要这些数据来避免不变错误 - 如果它们不在缓存中,我完全可以使用空字符串作为认值,这些值无论如何都不会显示在 UI 中的任何位置。>

有没有办法从缓存中读取部分片段?有没有更好的方法获取乐观响应的数据?

解决方法

我猜您使用了包含您需要的所有数据的表单中的代码段。因此,您可以通过参数将所需数据传递给 useEditPerson 钩子,然后在乐观响应中使用,然后您就不需要使用 gqlClient。