Last active
May 5, 2022 15:22
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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