首页 > 解决方案 > 使用 apollo 客户端创建自定义 useSubscription 钩子

问题描述

我想知道一件事。在我的项目中,每次订阅后我都会更新 apollo 缓存。根据 DRY 规则,我意识到重复自己,我决定编写我的自定义订阅挂钩。Hook 正在工作,但我觉得这不是正确的代码。有人对此有更好的解决方案吗?

useSubscriptionWithCache.ts

type ApplyFunc = (exisitingData: any, newData: any) => any;

const useSubscriptionWithCache = (
   subscription: DocumentNode | TypedDocumentNode,
   variables: object,
   newDataFieldName: string,
   updatedFieldName: string,
   applyFunc: ApplyFunc
) => {
   useSubscription(subscription, {
      variables: {
         ...variables,
      },
      onSubscriptionData: ({ client, subscriptionData: { data } }) => {
         if (data) {
            const newData = data[newDataFieldName]?.data;
            client.cache.modify({
               fields: {
                  [updatedFieldName]: (existingData = []) => {
                     return {
                        data: applyFunc(existingData, newData),
                     };
                  },
               },
            });
         }
      },
   });
};

如果我想在一个组件中使用

useSubscriptionWithCache(
      CREATED_CUSTOMER_SPECIAL_PACKAGE_SUBSCRIPTION,
      {
         token,
         customer: customer._id,
      },
      'createdCustomerSpecialPackage',
      'products',
      (existing, newData) => [...existing.data, newData]
   );

标签: reactjsreact-hooksapollo-clientsubscription

解决方案


推荐阅读