Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save oirodolfo/dd21022b55a18159ddeca17940c61762 to your computer and use it in GitHub Desktop.
Save oirodolfo/dd21022b55a18159ddeca17940c61762 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) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment