Last active
April 1, 2026 02:55
-
-
Save lourd/eae2266d619a5f1a7f6eb47e7dc735b7 to your computer and use it in GitHub Desktop.
Hook for returning a cached promise from a TanStack React Query to `use` in child component
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, | |
| Query, | |
| QueryClient, | |
| QueryKey, | |
| } from "@tanstack/react-query"; | |
| /** | |
| * Returns a function hooked up to the React Query cache that calls `queryClient.fetchQuery` or | |
| * returns the existing, cached promise. | |
| */ | |
| export function useFetchQuery(queryClient: QueryClient) { | |
| return function fetchQueryWithCachedPromise< | |
| TQueryFnData, | |
| TError, | |
| TData, | |
| TQueryKey extends QueryKey, | |
| >( | |
| options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>, | |
| ): Promise<TData> { | |
| const query = queryClient | |
| .getQueryCache() | |
| .find<TQueryFnData, TError, TData>(options) as | |
| | Query<TQueryFnData, TError, TData, TQueryKey> | |
| | undefined; | |
| if (!query?.promise) { | |
| return queryClient.fetchQuery(options); | |
| } | |
| if (query.state.status === "pending") { | |
| return query.promise; | |
| } | |
| const time = | |
| typeof options.staleTime === "function" | |
| ? options.staleTime(query) | |
| : options.staleTime; | |
| const isStale = query.isStaleByTime(time); | |
| if (isStale) { | |
| return queryClient.fetchQuery(options); | |
| } | |
| return query.promise; | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment