javascript - 使用 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 }];
};
解决方案
推荐阅读
- google-bigquery - 在 BigQuery 中查询账户连续负余额天数
- r - (纵向数据)使用每个 ID 的最后一个值创建新变量
- r - simr:如何在 lm() 或 aov() 模型中指定预期效果大小?
- python-3.x - 有没有办法让这段代码不那么可怕?蟒蛇 3
- kubernetes - 为什么 Kubernetes pod 运行的是旧镜像?
- ruby-on-rails - 如何在数组列中搜索多个字符串
- javascript - D3js:将 v3 升级到 v5
- css - 在 Angular 7 组件之间共享数据
- ruby-on-rails - 从 Rails 4 升级到 Rails 5 后,自定义错误处理不再起作用
- angular - 角度 - 如何只添加一次全局动画触发器