【问题标题】:Reusing data cached from one query in another在另一个查询中重用从一个查询缓存的数据
【发布时间】:2019-07-26 05:25:27
【问题描述】:

给定一个简单的 graphql 模式,如下所示:

type Contact {
    id: ID!
    name: String
}

type Query {
    RecentContacts: [Contact]
    Contact(id: ID!): Contact
}

如果我查询最近的联系人:

const GET_RECENT_CONTACTS = gql`
    query RecentContacts {
        RecentContacts {
          id
          name
        }
    }`

<Query client={client} query={GET_RECENT_CONTACTS}>
    {({loading, error, data}) => { /* etc... */ }}
</Query>

并接收数据,例如id 为 1 和 2 的联系人,缓存如下:

ROOT_QUERY
    RecentContacts: [Contact]
        0:  Contact:1
              id: 1
              name: Jack
        1:  Contact:2
              id: 2
              name: Jill

有没有办法让 Apollo 知道它可以将已缓存的条目用于查询 Contact(id: 1)Contact(id: 2),而无需发出另一个网络请求来恢复缓存中已经存在的数据?

具体来说,我希望这个查询在查询RecentContacts 之后不必发出网络请求,因为它需要的数据已经在缓存中(尽管从调用不同的查询返回):

const GET_CONTACT = gql`
    query Contact($id: ID!){
        Contact(id: $id){
          id
          name
        }
    }

<Query client={client} query={GET_CONTACT} variables={{id: 1}}>
    {({loading, error, data}) => {/* etc... */}}
</Query>

【问题讨论】:

    标签: apollo react-apollo apollo-client


    【解决方案1】:

    您可以使用cache redirects 来做到这一点。这是修改后的文档中的示例以使用您的架构:

    import { InMemoryCache } from 'apollo-cache-inmemory';
    
    const cache = new InMemoryCache({
      cacheRedirects: {
        Query: {
          User: (_, args, { getCacheKey }) =>
            getCacheKey({ __typename: 'User', id: args.id })
        },
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2019-09-04
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多