How to force Apollo Client to use cached data

857 views Asked by At

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

There are 1 answers

5
Daniel Rearden On BEST ANSWER

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)