Created
February 9, 2022 18:57
-
-
Save dan-cooke/171b8e43e0753cf6235706c8e63b3dc7 to your computer and use it in GitHub Desktop.
Fully typed useLazyQuery for `react-query`
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 { useCallback, useState } from 'react'; | |
import { | |
QueryFunction, | |
QueryKey, | |
useQuery, | |
UseQueryOptions, | |
UseQueryResult, | |
} from 'react-query'; | |
type UseQueryParams = Parameters<typeof useQuery>; | |
export default function useLazyQuery<TData, TError>( | |
key: UseQueryParams[0], | |
fetchFn: QueryFunction<TData, QueryKey>, | |
options?: Omit<UseQueryOptions<TData, TError, unknown, QueryKey>, 'queryKey' | 'queryFn'> | |
): [() => void, UseQueryResult<unknown, unknown>] { | |
const [enabled, setEnabled] = useState(false); | |
const query = useQuery<TData, TError, unknown, QueryKey>(key, fetchFn, { | |
...(options || {}), | |
enabled, | |
}); | |
const trigger = useCallback(() => { | |
if (!enabled) { | |
setEnabled(true); | |
} | |
}, [fetchFn, enabled]); | |
return [trigger, query]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
): [() => void, UseQueryResult<TData, TError>] => {
const query = useQuery<TData, TError, TData, QueryKey>
Provide
TData
instead ofunknown