首页 > 解决方案 > 如何获取 apollo 客户端缓存内容并在查询中将其用作输入类型?

问题描述

我正在使用 apollo 客户端开发一个 react native 应用程序,我需要有 2 个屏幕: 屏幕 A:显示配置文件列表 屏幕 B:显示一些必须应用于屏幕 A 的过滤器

所以我的想法是使用 apollo 客户端缓存将过滤器的状态保存在屏幕 B 中,然后返回屏幕 A 并以某种方式重新获取应用的新过滤器。

由于我需要在每个请求上向服务器发送几个过滤器,因此我也在考虑使用输入类型,这样我就可以以对象的形式发送过滤器,而不是逗号分隔的参数列表。

因此,查看来自 apollo 客户端的文档,有一个部分用于管理本地阶段。在那里,我找到了一个名为Using @client fields as variables的小节。基本上,这部分告诉您如何获取存储在缓存中的任何过滤器并将其作为查询的一部分发送。

但是,我总是收到以下错误: Invariant Violation: Missing selection set for an object of type ProfileParameters returned for query field profileParameters

一些代码:

这就是我初始化缓存存储的方式,目前,它只包含 page 和 pageSize 但它将包含更多参数。

const cache = new InMemoryCache({
  cacheRedirects: {
    Query: {
      profile: (_, {id}, {getCacheKey}) =>
        getCacheKey({__typename: 'Profile', id: id}),
    },
  },
});

cache.writeData({
  data: {
    profileParameters: {
      __typename: 'ProfileParameters',
      page: 0,
      pageSize: 25,
    },
  },
});

const client = new ApolloClient({
  uri: 'http://192.168.1.102:3000/graphql',
  cache: cache,
  resolvers: {},
});

这是查询组件和查询:

const PROFILES_QUERY = gql`
      query getFilteredProfiles($type: String, $parameters: ProfileParameters) {
        profileParameters @client @export(as: "parameters")
        profiles(type: $type, parameters: $parameters) {
          id
          name
          termOfEntry
          sport
          sportPosition
          gpa
          avatarUrl
          imageUrl
          nationality
          countryOfResidence
          dateOfBirth
          annualBudget
          career
          satScore
          toeflScore
          graduationDate
        }
      }
    `;
          <Query
            query={PROFILES_QUERY}
            variables={{
              type: this.PROFILE_TYPE,
            }}> 
               ...
          </Query>

在变量对象中传递了一个类型变量。这来自类中的局部变量。

此外,屏幕 B 尚不存在,但缓存正在初始化,我想读取其中的任何内容,以便将这些过滤器发送到服务器。

标签: react-nativegraphqlapollo-client

解决方案


推荐阅读