How to force Apollo Client to use cached data

谁都会走 提交于 2021-02-08 07:52:37

问题


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
}

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?


回答1:


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.

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)


来源:https://stackoverflow.com/questions/45922127/how-to-force-apollo-client-to-use-cached-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!