![](/img/trans.png)
[英]How to use apolloClient's 'onSuccess' only once the useMutation has executed successfully
[英]How to best use ApolloClient / InMemoryCache and enable Cache on demand for API's?
我想重构当前代码以使用 ApolloClient 构造函数来缓存信息,并且仅在请求数据尚未缓存时才查询新数据 -
目前我正在使用 fetchPolicy 来缓存用户 ID,但据我所知,有一种方法可以使用 apollo 进行缓存。
async fetchRecipients(userIds: string[]) {
//TODO: How to refactor and use apollo cache?
const result = await client?.query({
query: MembersBySFIDs,
variables: {sfids: userIds},
fetchPolicy: 'cache-first',
});
if (result?.data?.membersBySFIDs) {
await dispatch.newChatMessage.setRecipients(result.data.membersBySFIDs);
} else {
throw new Error('Members not found');
}
}
这是我到目前为止所尝试的,我认为我没有正确使用它,感谢任何帮助:
import { InMemoryCache, ApolloClient } from '@apollo/client';
const result = new ApolloClient({
cache: new InMemoryCache()
});
async fetchRecipients(userIds: string[]) {
const result = await client?.query({
query: MembersBySFIDs,
variables: {sfids: userIds},
fetchPolicy: 'cache-and-network'
});
if (result?.data?.membersBySFIDs) {
await dispatch.newChatMessage.setRecipients(result.data.membersBySFIDs);
} else {
throw new Error('Members not found');
}
}
您可以通过在defaultOptions
中将ApolloClient
的默认fetchPolicy
配置为cache-first
来设置client.query
的默认行为,如下所示。
像这样的东西:
import { InMemoryCache, ApolloClient } from '@apollo/client';
const client = new ApolloClient({
cache: new InMemoryCache(),
defaultOptions: {
query: {
fetchPolicy: "cache-first"
}
}
});
async fetchRecipients(userIds: string[]) {
const result = await client?.query({
query: MembersBySFIDs,
variables: {sfids: userIds},
});
// do whatever you want with the result here
}
希望你觉得这很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.