2

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?

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297

1 Answers1

2

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)
Daniel Rearden
  • 80,636
  • 11
  • 185
  • 183
  • 1
    So there is no way to get the data directly by there identifier? Cause this is what I understand from this article: https://dev-blog.apollodata.com/the-concepts-of-graphql-bc68bd819be3 – Andreas Köberle Aug 29 '17 at 06:51
  • I also wonder how could I add new widgets to the list to force and force a rerendering. – Andreas Köberle Aug 29 '17 at 07:48
  • 1
    Just found out about the `update` function in `mutate`. Works like a charm. – Andreas Köberle Aug 29 '17 at 11:54
  • @AndreasKöberle I am facing same problem, did you find any good solution or went with this one ? – Vano Oct 14 '20 at 12:09
  • If someone is still looking for answer, you can check my question and response here https://stackoverflow.com/questions/64349978/how-to-force-apollo-client-to-use-cached-data-for-detail-view-page/64354242#64354242 – Vano Oct 14 '20 at 13:53