Skip to content

Commit

Permalink
Use reobserve rather than refetch for useLazyQuery exec function.
Browse files Browse the repository at this point in the history
This is the most important commit of the PR, since it fixes issue #9375.
  • Loading branch information
benjamn committed Mar 29, 2022
1 parent d5bddd1 commit cdcda10
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/react/hooks/useLazyQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,19 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
);

const execOptionsRef = useRef<Partial<LazyQueryHookOptions<TData, TVariables>>>();
const defaultOptions = internalState.client.defaultOptions.watchQuery;
const initialFetchPolicy =
(options && options.fetchPolicy) ||
(execOptionsRef.current && execOptionsRef.current.fetchPolicy) ||
(defaultOptions && defaultOptions.fetchPolicy) ||
"cache-first";

const useQueryResult = internalState.useQuery({
...options,
...execOptionsRef.current,
// We don’t set skip to execution.called, because some useQuery SSR code
// checks skip for some reason.
fetchPolicy: execOptionsRef.current ? options?.fetchPolicy : 'standby',
fetchPolicy: execOptionsRef.current ? initialFetchPolicy : 'standby',
skip: undefined,
});

Expand Down Expand Up @@ -65,13 +72,18 @@ export function useLazyQuery<TData = any, TVariables = OperationVariables>(
const execute = useCallback<
LazyQueryResultTuple<TData, TVariables>[0]
>(executeOptions => {
execOptionsRef.current = executeOptions;
internalState.forceUpdate();
executeOptions = execOptionsRef.current = {
...executeOptions, // Works when executeOptions initially falsy/undefined
fetchPolicy: executeOptions && executeOptions.fetchPolicy || initialFetchPolicy,
};

const promise = result.refetch(executeOptions?.variables)
const promise = result.observable.reobserve(executeOptions)
.then(apolloQueryResult => internalState.toQueryResult(apolloQueryResult))
.then(queryResult => Object.assign(queryResult, eagerMethods));

// Deliver the loading state for this reobservation immediately.
internalState.forceUpdate();

// Because the return value of `useLazyQuery` is usually floated, we need
// to catch the promise to prevent unhandled rejections.
promise.catch(() => {});
Expand Down

0 comments on commit cdcda10

Please sign in to comment.