Forked from itimoshenko/useLazyQuery for "react-query"
Last active
November 6, 2025 10:14
-
-
Save giammyisjammy/9c2042d6073abb170d3afb9e5f4910c7 to your computer and use it in GitHub Desktop.
useLazyQuery for "react-query"
This file contains hidden or 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 { FetchQueryOptions, QueryFunction, QueryKey, useQueryClient } from '@tanstack/react-query' | |
| import { useCallback, useMemo, useState } from 'react' | |
| export function useLazyQuery< | |
| TQueryFnData = unknown, | |
| TError = unknown, | |
| TData = TQueryFnData, | |
| TQueryKey extends QueryKey = QueryKey, | |
| >( | |
| queryFn: QueryFunction<TQueryFnData, TQueryKey>, | |
| options?: Omit<FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, 'queryKey' | 'queryFn'>, | |
| ) { | |
| const queryClient = useQueryClient() | |
| const [data, setData] = useState<TData>() | |
| const [isLoading, setIsLoading] = useState(false) | |
| const trigger = useCallback( | |
| async (queryKey: TQueryKey) => { | |
| setIsLoading(true) | |
| return await queryClient.ensureQueryData(queryKey, queryFn, options).then((res) => { | |
| setData(res) | |
| setIsLoading(false) | |
| return res | |
| }) | |
| }, | |
| [options, queryClient, queryFn], | |
| ) | |
| const result = useMemo( | |
| () => ({ | |
| trigger, | |
| isLoading, | |
| data, | |
| }), | |
| [data, isLoading, trigger], | |
| ) | |
| return result | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment