微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何最好地使用 ApolloClient / InMemoryCache 并按需为 API 启用缓存?

如何解决如何最好地使用 ApolloClient / InMemoryCache 并按需为 API 启用缓存?

我想折射当前代码以使用 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,fetchPolicy: 'cache-and-network'
  });

  if (result?.data?.membersBySFIDs) {
    await dispatch.newChatMessage.setRecipients(result.data.membersBySFIDs);
  } else {
    throw new Error('Members not found');
  }
}

解决方法

您可以通过将 client.query 的默认 ApolloClient 配置为 fetchPolicy 中的 cache-first 来设置 defaultOptions 的默认行为,如图here .

像这样:

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
 
}

希望这对您有帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。