Skip to content

Instantly share code, notes, and snippets.

@brendanmoore
Created November 2, 2020 09:14
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save brendanmoore/8cd239c5b35983936581b61922b09b2e to your computer and use it in GitHub Desktop.
Save brendanmoore/8cd239c5b35983936581b61922b09b2e to your computer and use it in GitHub Desktop.
function useCachedAbortiveQuery<T>(
query: DocumentNode,
variables: Record<string, unknown>,
deps: Array<any>
) {
const apolloClient = useApolloClient();
const [data, setData] = useState<T>();
const [error, setError] = useState<Error | null>(null);
const [loading, setLoading] = useState<boolean>(true);
useEffect(() => {
setLoading(true);
const watchedQuery = apolloClient.watchQuery<T>({
query,
variables,
fetchPolicy: 'cache-and-network'
});
const sub = watchedQuery.subscribe({
next(x) {
if (!x.partial) {
setData(x.data);
setError(null);
setLoading(false);
}
},
error(err) {
setError(err);
setLoading(false);
},
complete() {
setLoading(false);
}
});
return () => {
sub.unsubscribe();
};
}, deps);
return { data, error, loading, clearError: () => setError(null) };
}
@dave-flr
Copy link

and how can I do the same with useLazyQuey instead?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment