使用 ApolloLink,您可以生成链接afterware
以解析返回的响应,并在适当的情况下有条件地更新缓存。
import { ApolloLink } from "apollo-link";
import { createHttpLink } from "apollo-link-http";
const httpLink = createHttpLink({ uri: "/graphql" });
const updateDateCacheLink = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
const context = operation.getContext();
const { response: { headers } } = context;
/* conditionally update cache */
return response;
});
});
// use with apollo-client
const link = updateDateCacheLink.concat(httpLink);
或者,您可以考虑使用 HOC 返回一个组件,该组件实现 的update
回调useMutation
,该回调接收更新有效负载。这将避免重复并封装与您的请求一致的通用缓存逻辑。正如您所指出的,自定义钩子可以包装并用于代替 useMutation(未在下面显示)。
const withMutationCacheUpdate = args => Wrapped => {
return function(props) {
const [updateData] = useMutation(UPDATE_DATA, {
update(cache, { data: { newData } }) {
// Read relevant data from cache with cache.readQuery,
// then update using cache.writeQuery, cache.writeFragment
// or cache.modify as appropriate with returned payload and possibly args
},
})
return <Wrapped {...props} updateData={updateData} />
}
}
const config = {...}
const YourComponent = props => { ... }
const YourWrappedComponent = withMutationCacheUpdate(config)(YourComponent)