Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor useQuery to not use an internal class #11869

Merged
merged 33 commits into from
Jul 4, 2024
Merged
Changes from 1 commit
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
c2bd48b
extract hooks from InternalState
phryneas May 27, 2024
dc58beb
inline hooks and functions into each other, move `createWatchQueryOpt…
phryneas May 27, 2024
10466e5
move `executeQuery` to `useLazyQuery`
phryneas May 27, 2024
ea77f60
move more functions out
phryneas May 27, 2024
fde4c4d
move `unsafeHandlePartialRefetch` into `setResult`
phryneas May 28, 2024
e1b7ed7
remove `toQueryResultCache`, save transformed result in `internalStat…
phryneas May 29, 2024
9c865ca
fixup test
phryneas May 29, 2024
b5e1643
move `getDefaultFetchPolicy` out
phryneas May 29, 2024
b4c8bf9
move more functions out
phryneas May 29, 2024
12e19f9
moved all class methods out
phryneas May 29, 2024
24e4491
replace class with single mutable object
phryneas May 29, 2024
e31d953
move callbacks into their own ref
phryneas May 29, 2024
891e211
move `obsQueryFields` out of `internalState`
phryneas Jun 3, 2024
ec1c7a9
inline `useInternalState`
phryneas Jun 4, 2024
79566a8
redactor away `internalState.queryHookOptions`
phryneas Jun 4, 2024
873f24d
make function arguments more explicit
phryneas Jun 4, 2024
8bb445c
replace `internalState.watchQueryOptions` with `observable[lastWatchO…
phryneas Jun 5, 2024
635a32b
move observable fully into a readonly prop on internalState
phryneas Jun 5, 2024
d6de17f
remove all direct access to `internalState` after initializing
phryneas Jun 5, 2024
06d98ac
extract new `useInternalState` hook
phryneas Jun 5, 2024
7717b4f
extract `useResubscribeIfNecessary` hook
phryneas Jun 5, 2024
3889fff
add comment
phryneas Jun 5, 2024
da4b840
extract `bindObservableMethods`
phryneas Jun 7, 2024
f18b753
extract `useHandleSkip` and `useRegisterSSRObservable` hooks
phryneas Jun 7, 2024
8480ce6
extract useObservableSubscriptionResult hook
phryneas Jun 7, 2024
30b1769
change some method arguments. remove obsolete comment
phryneas Jun 7, 2024
c896885
curry `createMakeWatchQueryOptions`
phryneas Jun 7, 2024
1485651
bring function and hook argyuments into a common order
phryneas Jun 7, 2024
70f5aaf
Move `onQueryExecuted` into `useInternalState`
phryneas Jun 7, 2024
fed117b
some style adjustments to be more compiler-friendly
phryneas Jun 7, 2024
a69327c
remove R19 exception from test, chores
phryneas Jul 3, 2024
987aaad
Apply suggestions from code review
phryneas Jul 4, 2024
33c0fef
Merge branch 'release-3.11' into pr/rewrite-useQuery
phryneas Jul 4, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
109 changes: 52 additions & 57 deletions src/react/hooks/useQuery.ts
Original file line number Diff line number Diff line change
@@ -30,7 +30,6 @@ import type {
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { useApolloClient } from "./useApolloClient.js";
import {
canUseWeakMap,
compact,
isNonEmptyArray,
maybeDeepFreeze,
@@ -41,6 +40,12 @@ const {
prototype: { hasOwnProperty },
} = Object;

const originalResult = Symbol();
interface InternalQueryResult<TData, TVariables extends OperationVariables>
extends QueryResult<TData, TVariables> {
[originalResult]: ApolloQueryResult<TData>;
}

/**
* A hook for executing queries in an Apollo application.
*
@@ -165,14 +170,36 @@ export function useQueryWithInternalState<
options.onCompleted || InternalState.prototype.onCompleted;
internalState.onError = options.onError || InternalState.prototype.onError;

// See if there is an existing observable that was used to fetch the same
// data and if so, use it instead since it will contain the proper queryId
// to fetch the result set. This is used during SSR.
const obsQuery = (internalState.observable =
(renderPromises &&
renderPromises.getSSRObservable(internalState.watchQueryOptions)) ||
internalState.observable || // Reuse this.observable if possible (and not SSR)
internalState.client.watchQuery(internalState.getObsQueryOptions()));

internalState.obsQueryFields = React.useMemo(
() => ({
refetch: obsQuery.refetch.bind(obsQuery),
reobserve: obsQuery.reobserve.bind(obsQuery),
fetchMore: obsQuery.fetchMore.bind(obsQuery),
updateQuery: obsQuery.updateQuery.bind(obsQuery),
startPolling: obsQuery.startPolling.bind(obsQuery),
stopPolling: obsQuery.stopPolling.bind(obsQuery),
subscribeToMore: obsQuery.subscribeToMore.bind(obsQuery),
}),
[obsQuery]
);

if (
(renderPromises || internalState.client.disableNetworkFetches) &&
internalState.queryHookOptions.ssr === false &&
!internalState.queryHookOptions.skip
) {
// If SSR has been explicitly disabled, and this function has been called
// on the server side, return the default loading state.
internalState.result = ssrDisabledResult;
internalState.result = toQueryResult(ssrDisabledResult, internalState);
} else if (
internalState.queryHookOptions.skip ||
internalState.watchQueryOptions.fetchPolicy === "standby"
@@ -187,36 +214,14 @@ export function useQueryWithInternalState<
// previously received data is all of a sudden removed. Unfortunately,
// changing this is breaking, so we'll have to wait until Apollo Client 4.0
// to address this.
internalState.result = skipStandbyResult;
internalState.result = toQueryResult(skipStandbyResult, internalState);
} else if (
internalState.result === ssrDisabledResult ||
internalState.result === skipStandbyResult
internalState.result?.[originalResult] === ssrDisabledResult ||
internalState.result?.[originalResult] === skipStandbyResult
) {
internalState.result = void 0;
}

// See if there is an existing observable that was used to fetch the same
// data and if so, use it instead since it will contain the proper queryId
// to fetch the result set. This is used during SSR.
const obsQuery = (internalState.observable =
(renderPromises &&
renderPromises.getSSRObservable(internalState.watchQueryOptions)) ||
internalState.observable || // Reuse this.observable if possible (and not SSR)
internalState.client.watchQuery(internalState.getObsQueryOptions()));

internalState.obsQueryFields = React.useMemo(
() => ({
refetch: obsQuery.refetch.bind(obsQuery),
reobserve: obsQuery.reobserve.bind(obsQuery),
fetchMore: obsQuery.fetchMore.bind(obsQuery),
updateQuery: obsQuery.updateQuery.bind(obsQuery),
startPolling: obsQuery.startPolling.bind(obsQuery),
stopPolling: obsQuery.stopPolling.bind(obsQuery),
subscribeToMore: obsQuery.subscribeToMore.bind(obsQuery),
}),
[obsQuery]
);

const ssrAllowed = !(
internalState.queryHookOptions.ssr === false ||
internalState.queryHookOptions.skip
@@ -313,7 +318,7 @@ export function useQueryWithInternalState<
() => internalState.getCurrentResult()
);

return toQueryResult(result, internalState);
return result;
}

export function useInternalState<TData, TVariables extends OperationVariables>(
@@ -473,7 +478,7 @@ class InternalState<TData, TVariables extends OperationVariables> {

// These members are populated by getCurrentResult and setResult, and it's
// okay/normal for them to be initially undefined.
public result: undefined | ApolloQueryResult<TData>;
public result: undefined | InternalQueryResult<TData, TVariables>;
public previousData: undefined | TData;

public setResult(
@@ -484,11 +489,14 @@ class InternalState<TData, TVariables extends OperationVariables> {
if (previousResult && previousResult.data) {
this.previousData = previousResult.data;
}
this.result = unsafeHandlePartialRefetch(nextResult, this);
this.result = toQueryResult(
unsafeHandlePartialRefetch(nextResult, this),
this
);
// Calling state.setResult always triggers an update, though some call sites
// perform additional equality checks before committing to an update.
forceUpdate();
this.handleErrorOrCompleted(nextResult, previousResult);
this.handleErrorOrCompleted(nextResult, previousResult?.[originalResult]);
}

public handleErrorOrCompleted(
@@ -517,7 +525,7 @@ class InternalState<TData, TVariables extends OperationVariables> {
}
}

public getCurrentResult(): ApolloQueryResult<TData> {
public getCurrentResult(): QueryResult<TData, TVariables> {
// Using this.result as a cache ensures getCurrentResult continues returning
// the same (===) result object, unless state.setResult has been called, or
// we're doing server rendering and therefore override the result below.
@@ -528,14 +536,6 @@ class InternalState<TData, TVariables extends OperationVariables> {
}
return this.result!;
}

// This cache allows the referential stability of this.result (as returned by
// getCurrentResult) to translate into referential stability of the resulting
// QueryResult object returned by toQueryResult.
public toQueryResultCache = new (canUseWeakMap ? WeakMap : Map)<
ApolloQueryResult<TData>,
QueryResult<TData, TVariables>
>();
}

function toApolloError<TData>(
@@ -549,24 +549,19 @@ function toApolloError<TData>(
export function toQueryResult<TData, TVariables extends OperationVariables>(
result: ApolloQueryResult<TData>,
internalState: InternalState<TData, TVariables>
): QueryResult<TData, TVariables> {
let queryResult = internalState.toQueryResultCache.get(result);
if (queryResult) return queryResult;

): InternalQueryResult<TData, TVariables> {
const { data, partial, ...resultWithoutPartial } = result;
internalState.toQueryResultCache.set(
result,
(queryResult = {
data, // Ensure always defined, even if result.data is missing.
...resultWithoutPartial,
...internalState.obsQueryFields,
client: internalState.client,
observable: internalState.observable,
variables: internalState.observable.variables,
called: !internalState.queryHookOptions.skip,
previousData: internalState.previousData,
})
);
const queryResult: InternalQueryResult<TData, TVariables> = {
[originalResult]: result,
data, // Ensure always defined, even if result.data is missing.
...resultWithoutPartial,
...internalState.obsQueryFields,
client: internalState.client,
observable: internalState.observable,
variables: internalState.observable.variables,
called: !internalState.queryHookOptions.skip,
previousData: internalState.previousData,
};

if (!queryResult.error && isNonEmptyArray(result.errors)) {
// Until a set naming convention for networkError and graphQLErrors is