Last active
November 6, 2025 10:12
-
-
Save itimoshenko/43e4f2fadba74c8d48ffa36f00dfdf67 to your computer and use it in GitHub Desktop.
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