Magdy Zamel
Magdy Zamel

Reputation: 476

Apollo iOS swift Always get from Local cache GraphQl

When I use Apollo to deal with GraphQl API for every fetch in the first time only Apollo fetches from server else always fetch get from Local cache

let apollo = ApolloClient(url: URL(string: graphQLEndpoint)!)
let meetingsQuery = AllMeetingsQuery()
apollo.fetch(query: meetingsQuery) { [weak self] result, error in
  guard let meetings = result?.data?.allMeetings else { return }
  print(conferences.count)
  self?.conferences = conferences.map {$0.fragments.meetingDetails }
}

Upvotes: 3

Views: 2074

Answers (1)

Magdy Zamel
Magdy Zamel

Reputation: 476

Every query from the server can be controlled by CachePolicy

A Cache policy that specifies whether results should be fetched from the server or loaded from the local cache.

public enum CachePolicy {
  /// Return data from the cache if available, else fetch results from the server.
  case returnCacheDataElseFetch
  ///  Always fetch results from the server.
  case fetchIgnoringCacheData
  /// Return data from the cache if available, else return nil.
  case returnCacheDataDontFetch
}

The default value is returnCacheDataElseFetch which mean Apollo return data from the cache if available, else fetch results from the server.

I solved the problem by changing the cachePolicy with fetchIgnoringCacheData

apollo.fetch(query: meetingsQuery ,cachePolicy: .fetchIgnoringCacheData)  { [weak self] result, error in
  guard let meetings = result?.data?.allMeetings else { return }
  print(conferences.count)
}

Upvotes: 11

Related Questions