Created
November 2, 2020 09:14
-
-
Save brendanmoore/8cd239c5b35983936581b61922b09b2e to your computer and use it in GitHub Desktop.
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
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
and how can I do the same with
useLazyQuey
instead?