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

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

问题描述

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

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
}

后来我渲染了这个小部件,其中每个react组件都被另一个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
    }
}

那么有什么地方可以检查为什么阿波罗不使用缓存的吗?

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客户端使用缓存的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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