首页 > 解决方案 > 使用 Apollo 客户端和 React 自定义 useMutation 钩子

问题描述

在使用 Apollo 客户端时,我发现为每个需要立即更新 UI 的突变手动更新缓存非常繁琐。因此,我决定尝试制作一个自动更新缓存的自定义钩子。

钩子有效,但它似乎有点“hacky”,我担心它可能会扰乱缓存的正常功能。所以我只是想问一下这个钩子是否应该可以正常工作?

这是代码(其中mutationName是实际的 graphql 突变名称,fieldName是与突变对应的原始 graphql 查询名称):

export const useMutationWithCacheUpdate = (
  mutation,
  mutationName,
  fieldName
) => {
  const [createMutation, { data, loading, error }] = useMutation(mutation, {
    update(cache, { data }) {
      data = data[mutationName];
      cache.modify({
        fields: {
          [fieldName]: (existingItems = []) => {
            const newItemRef = cache.writeFragment({
              data: data,
              fragment: gql`
                  fragment newItem on ${fieldName} {
                    id
                    type
                  }
                `,
            });
            return [...existingItems, newItemRef];
          },
        },
      });
    },
  });
  return [createMutation, { data, loading, error }];
};

标签: javascriptreactjsgraphqlapolloapollo-client

解决方案


推荐阅读