如何最好地使用 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
 
}

希望这对您有帮助。