Created
May 28, 2019 20:33
-
-
Save smkhalsa/b4c663f27292c0ad4d17442e40e26b35 to your computer and use it in GitHub Desktop.
GraphQL Query Hook
This file contains 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
import 'package:flutter/widgets.dart'; | |
import 'package:flutter_hooks/flutter_hooks.dart'; | |
import 'package:graphql/internal.dart'; | |
import 'package:graphql/client.dart'; | |
QueryResult useQuery( | |
{@required GraphQLClient client, @required QueryOptions options}) { | |
return Hook.use(_QueryHook(client: client, options: options)); | |
} | |
class _QueryHook extends Hook<QueryResult> { | |
final QueryOptions options; | |
final GraphQLClient client; | |
_QueryHook({@required this.options, @required this.client}); | |
@override | |
_QueryHookState createState() => _QueryHookState(); | |
} | |
class _QueryHookState<T> extends HookState<QueryResult, _QueryHook> { | |
ObservableQuery observableQuery; | |
WatchQueryOptions get _options { | |
FetchPolicy fetchPolicy = hook.options.fetchPolicy; | |
if (fetchPolicy == FetchPolicy.cacheFirst) { | |
fetchPolicy = FetchPolicy.cacheAndNetwork; | |
} | |
return WatchQueryOptions( | |
document: hook.options.document, | |
variables: hook.options.variables, | |
fetchPolicy: fetchPolicy, | |
errorPolicy: hook.options.errorPolicy, | |
pollInterval: hook.options.pollInterval, | |
fetchResults: true, | |
context: hook.options.context, | |
optimisticResult: hook.options.optimisticResult, | |
); | |
} | |
void _initQuery() { | |
observableQuery?.close(); | |
observableQuery = hook.client.watchQuery(_options); | |
} | |
@override | |
void initHook() { | |
super.initHook(); | |
_initQuery(); | |
} | |
@override | |
void didUpdateHook(_QueryHook oldWidget) { | |
super.didUpdateHook(oldWidget); | |
if (!observableQuery.options.areEqualTo(_options)) { | |
_initQuery(); | |
} | |
} | |
@override | |
void dispose() { | |
observableQuery?.close(); | |
super.dispose(); | |
} | |
@override | |
QueryResult build(BuildContext context) { | |
return useStream<QueryResult>( | |
observableQuery.stream, | |
initialData: QueryResult( | |
loading: true, | |
), | |
).data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment