2
votes

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 }
}
1

1 Answers

9
votes

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)
}