Skip to content

Instantly share code, notes, and snippets.

@natpenguin
Last active May 5, 2022 15:22
Show Gist options
  • Save natpenguin/1cfef0e16d555930f182efc73501f767 to your computer and use it in GitHub Desktop.
Save natpenguin/1cfef0e16d555930f182efc73501f767 to your computer and use it in GitHub Desktop.
A propertyWrapper for supporting declarative data fetching on SwiftUI with GraphQL(using apollo-ios)
@propertyWrapper
struct Query<Query: GraphQLQuery>: DynamicProperty {
enum NetworkState {
case notFetching
case fetching
case success(Query.Data)
case failure
}
@State var wrappedValue: NetworkState = .notFetching
@Environment(\.apolloClient)
private var client
func callAsFunction(
query: Query,
cachePolicy: CachePolicy = .returnCacheDataElseFetch,
contextIdentifier: UUID? = nil,
queue: DispatchQueue = .global()
) {
wrappedValue = .fetching
client.fetch(
query: query,
cachePolicy: cachePolicy,
contextIdentifier: contextIdentifier,
queue: queue
) { result in
switch result {
case .success(let result):
if let _ = result.errors {
self.wrappedValue = .failure
} else if let data = result.data {
self.wrappedValue = .success(data)
} else {
self.wrappedValue = .failure
}
case .failure(let error):
print(error.localizedDescription)
self.wrappedValue = .failure
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment