From a189fe42c5e62039a7b78fbacbffae63a5f45359 Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Tue, 15 Mar 2022 12:23:46 -0400 Subject: [PATCH] Use useRef instead of useState for useLazyQuery execution state. --- src/react/hooks/useLazyQuery.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/src/react/hooks/useLazyQuery.ts b/src/react/hooks/useLazyQuery.ts index c90054395a9..2d5fa2d1507 100644 --- a/src/react/hooks/useLazyQuery.ts +++ b/src/react/hooks/useLazyQuery.ts @@ -1,6 +1,6 @@ import { DocumentNode } from 'graphql'; import { TypedDocumentNode } from '@graphql-typed-document-node/core'; -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useMemo, useRef } from 'react'; import { OperationVariables } from '../../core'; import { @@ -30,10 +30,11 @@ export function useLazyQuery( query, ); - const [execution, setExecution] = useState<{ - called: boolean, + const execRef = useRef<{ + called: boolean; options?: Partial>; - }>({ + }>(); + const execution = execRef.current || (execRef.current = { called: false, }); @@ -57,7 +58,8 @@ export function useLazyQuery( for (const key of EAGER_METHODS) { const method = result[key]; eagerMethods[key] = (...args: any) => { - setExecution((execution) => ({ ...execution, called: true })); + execution.called = true; + internalState.forceUpdate(); return (method as any)(...args); }; } @@ -70,7 +72,10 @@ export function useLazyQuery( const execute = useCallback< LazyQueryResultTuple[0] >(executeOptions => { - setExecution({ called: true, options: executeOptions }); + execution.called = true; + execution.options = executeOptions; + internalState.forceUpdate(); + const promise = result.refetch(executeOptions?.variables) .then(apolloQueryResult => internalState.toQueryResult(apolloQueryResult)) .then(queryResult => Object.assign(queryResult, eagerMethods));