如何强制 Apollo Client 使用缓存数据 [英] How to force Apollo Client to use cached data

查看:35
本文介绍了如何强制 Apollo Client 使用缓存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个最初加载小部件列表的应用程序:

We have an application that initially load a list of widgets:

query Widgets() {
    widgets() {
        ...Widgets
    }
}

fragment Widgets on Widgets {
    name
    description
    rootWidget
    widgets {
        ...WidgetInterface
    }
}

fragment WidgetInterface on WidgetInterface {
    id
    name
    description
    type
}

稍后我渲染这个小部件,其中每个反应组件都用另一个 graphql 调用包装,以获取单个小部件的数据.当我们最初获取这些数据时,我希望 apollo 从本地存储中获取数据,但它总是使服务器调用

later on I render this widgets, where every react component is wrapped with another graphql call to get the data for a single widget. As we fetch this data initially I would expect apollo get the data from local store, but it always make the server call

#import '../fragments/WidgetInterface.graphql'

query Widget($id: ID!) {
    widgetDetails(id: $id) {
        ...WidgetInterface
    }
}

那么可以检查一下为什么 apollo 不使用缓存的吗?

So is there away to check why apollo not uses the cached ones?

推荐答案

Apollo 按查询缓存您的查询结果.它从服务器而不是缓存中获取数据的原因是第一次渲染组件时,您从未进行过 widgetDetails 查询,只有一个 widgets 查询.

Apollo caches your query results by query. The reason it's grabbing the data from the server instead of the cache is that the first time you render your component, you've never made a widgetDetails query, only a widgets one.

如果您想避免使用 widgetDetails 查询,您可以将组件设置为使用 widgets 查询,而只需自己按 id 过滤结果.类似的东西:

If you want to avoid making the widgetDetails query, you can set up your component to use the widgets query instead and just filter the results by id yourself. Something like:

graphql(WIDGETS_QUERY, {
  props: ({data, ownProps}) => ({ widget: data.widgets.filter(w => w === ownProps.widgetId) })
})(MyComponent)

这篇关于如何强制 Apollo Client 使用缓存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆