reactjs - 使用 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]
);
解决方案
推荐阅读
- linux - 从 1 行获取带有 awk 的字符串/短语
- visual-studio - Hololens 2 模拟器无法识别输入
- javascript - 将函数 VARIABLE 传递给事件侦听器与传递函数 REFERENCE 有什么区别?
- python - 如何在循环中从 BeautifulSoup 中的 span 标签获取文本
- go - Bazel build missing strict dependencies
- mongodb - mongo-go-driver get inserted document
- javascript - Using jQuery/js counter with Owl Carousel to display two digits in navigation
- javascript - Converting JS arrays into objects from table
- docker - Docker flooding syslog with run-docker-runtime logs
- javascript - Combine two URLSearchParams()