Skip to content

Commit

Permalink
Use useRef instead of useState for useLazyQuery execution state.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Mar 29, 2022
1 parent 09c1904 commit a189fe4
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions src/react/hooks/useLazyQuery.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -30,10 +30,11 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
query,
);

const [execution, setExecution] = useState<{
called: boolean,
const execRef = useRef<{
called: boolean;
options?: Partial<LazyQueryHookOptions<TData, TVariables>>;
}>({
}>();
const execution = execRef.current || (execRef.current = {
called: false,
});

Expand All @@ -57,7 +58,8 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
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);
};
}
Expand All @@ -70,7 +72,10 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
const execute = useCallback<
LazyQueryResultTuple<TData, TVariables>[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));
Expand Down

0 comments on commit a189fe4

Please sign in to comment.