Skip to content

Instantly share code, notes, and snippets.

@dan-cooke
Created February 9, 2022 18:57
Show Gist options
  • Save dan-cooke/171b8e43e0753cf6235706c8e63b3dc7 to your computer and use it in GitHub Desktop.
Save dan-cooke/171b8e43e0753cf6235706c8e63b3dc7 to your computer and use it in GitHub Desktop.

Revisions

  1. dan-cooke created this gist Feb 9, 2022.
    31 changes: 31 additions & 0 deletions useLazyQuery.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    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];
    }