Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
at main 1.0 kB view raw
1import type { DocumentNode } from 'graphql'; 2import { useRef, useMemo } from 'preact/hooks'; 3import type { 4 AnyVariables, 5 TypedDocumentNode, 6 GraphQLRequest, 7} from '@urql/core'; 8import { createRequest } from '@urql/core'; 9 10/** Creates a request from a query and variables but preserves reference equality if the key isn't changing 11 * @internal 12 */ 13export function useRequest< 14 Data = any, 15 Variables extends AnyVariables = AnyVariables, 16>( 17 query: string | DocumentNode | TypedDocumentNode<Data, Variables>, 18 variables: Variables 19): GraphQLRequest<Data, Variables> { 20 const prev = useRef<undefined | GraphQLRequest<Data, Variables>>(undefined); 21 return useMemo(() => { 22 const request = createRequest<Data, Variables>(query, variables); 23 // We manually ensure reference equality if the key hasn't changed 24 if (prev.current !== undefined && prev.current.key === request.key) { 25 return prev.current; 26 } else { 27 prev.current = request; 28 return request; 29 } 30 }, [query, variables]); 31}