Initial Sample.

This commit is contained in:
2024-06-03 20:23:50 +05:30
parent ef2b65f673
commit 5269ec3c66
2575 changed files with 282312 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
export declare const skipToken: unique symbol;
export type SkipToken = typeof skipToken;
//# sourceMappingURL=constants.d.ts.map

View File

@@ -0,0 +1,2 @@
export var skipToken = Symbol.for("apollo.skipToken");
//# sourceMappingURL=constants.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/react/hooks/constants.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,IAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC","sourcesContent":["export const skipToken = Symbol.for(\"apollo.skipToken\");\nexport type SkipToken = typeof skipToken;\n"]}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,21 @@
import "../../utilities/globals/index.js";
export * from "./useApolloClient.js";
export * from "./useLazyQuery.js";
export * from "./useMutation.js";
export { useQuery } from "./useQuery.js";
export * from "./useSubscription.js";
export * from "./useReactiveVar.js";
export * from "./useFragment.js";
export type { UseSuspenseQueryResult } from "./useSuspenseQuery.js";
export { useSuspenseQuery } from "./useSuspenseQuery.js";
export type { UseBackgroundQueryResult } from "./useBackgroundQuery.js";
export { useBackgroundQuery } from "./useBackgroundQuery.js";
export type { LoadQueryFunction, UseLoadableQueryResult, } from "./useLoadableQuery.js";
export { useLoadableQuery } from "./useLoadableQuery.js";
export type { UseQueryRefHandlersResult } from "./useQueryRefHandlers.js";
export { useQueryRefHandlers } from "./useQueryRefHandlers.js";
export type { UseReadQueryResult } from "./useReadQuery.js";
export { useReadQuery } from "./useReadQuery.js";
export { skipToken } from "./constants.js";
export type { SkipToken } from "./constants.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,15 @@
import "../../utilities/globals/index.js";
export * from "./useApolloClient.js";
export * from "./useLazyQuery.js";
export * from "./useMutation.js";
export { useQuery } from "./useQuery.js";
export * from "./useSubscription.js";
export * from "./useReactiveVar.js";
export * from "./useFragment.js";
export { useSuspenseQuery } from "./useSuspenseQuery.js";
export { useBackgroundQuery } from "./useBackgroundQuery.js";
export { useLoadableQuery } from "./useLoadableQuery.js";
export { useQueryRefHandlers } from "./useQueryRefHandlers.js";
export { useReadQuery } from "./useReadQuery.js";
export { skipToken } from "./constants.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/react/hooks/index.ts"],"names":[],"mappings":"AAAA,OAAO,kCAAkC,CAAC;AAE1C,cAAc,sBAAsB,CAAC;AACrC,cAAc,mBAAmB,CAAC;AAClC,cAAc,kBAAkB,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,kBAAkB,CAAC;AAEjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAK7D,OAAO,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAEzD,OAAO,EAAE,mBAAmB,EAAE,MAAM,0BAA0B,CAAC;AAE/D,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC","sourcesContent":["import \"../../utilities/globals/index.js\";\n\nexport * from \"./useApolloClient.js\";\nexport * from \"./useLazyQuery.js\";\nexport * from \"./useMutation.js\";\nexport { useQuery } from \"./useQuery.js\";\nexport * from \"./useSubscription.js\";\nexport * from \"./useReactiveVar.js\";\nexport * from \"./useFragment.js\";\nexport type { UseSuspenseQueryResult } from \"./useSuspenseQuery.js\";\nexport { useSuspenseQuery } from \"./useSuspenseQuery.js\";\nexport type { UseBackgroundQueryResult } from \"./useBackgroundQuery.js\";\nexport { useBackgroundQuery } from \"./useBackgroundQuery.js\";\nexport type {\n LoadQueryFunction,\n UseLoadableQueryResult,\n} from \"./useLoadableQuery.js\";\nexport { useLoadableQuery } from \"./useLoadableQuery.js\";\nexport type { UseQueryRefHandlersResult } from \"./useQueryRefHandlers.js\";\nexport { useQueryRefHandlers } from \"./useQueryRefHandlers.js\";\nexport type { UseReadQueryResult } from \"./useReadQuery.js\";\nexport { useReadQuery } from \"./useReadQuery.js\";\nexport { skipToken } from \"./constants.js\";\nexport type { SkipToken } from \"./constants.js\";\n"]}

View File

@@ -0,0 +1,4 @@
type Use = <T>(promise: Promise<T>) => T;
export declare const __use: Use;
export {};
//# sourceMappingURL=__use.d.ts.map

View File

@@ -0,0 +1,22 @@
import { wrapPromiseWithState } from "../../../utilities/index.js";
import * as React from "rehackt";
// Prevent webpack from complaining about our feature detection of the
// use property of the React namespace, which is expected not
// to exist when using current stable versions, and that's fine.
var useKey = "use";
var realHook = React[useKey];
// This is named with two underscores to allow this hook to evade typical rules of
// hooks (i.e. it can be used conditionally)
export var __use = realHook ||
function __use(promise) {
var statefulPromise = wrapPromiseWithState(promise);
switch (statefulPromise.status) {
case "pending":
throw statefulPromise;
case "rejected":
throw statefulPromise.reason;
case "fulfilled":
return statefulPromise.value;
}
};
//# sourceMappingURL=__use.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"__use.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/__use.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAGjC,sEAAsE;AACtE,6DAA6D;AAC7D,gEAAgE;AAChE,IAAM,MAAM,GAAG,KAA2B,CAAC;AAC3C,IAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAoB,CAAC;AAElD,kFAAkF;AAClF,4CAA4C;AAC5C,MAAM,CAAC,IAAM,KAAK,GAChB,QAAQ;IACR,SAAS,KAAK,CAAS,OAAwB;QAC7C,IAAM,eAAe,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;QAEtD,QAAQ,eAAe,CAAC,MAAM,EAAE,CAAC;YAC/B,KAAK,SAAS;gBACZ,MAAM,eAAe,CAAC;YACxB,KAAK,UAAU;gBACb,MAAM,eAAe,CAAC,MAAM,CAAC;YAC/B,KAAK,WAAW;gBACd,OAAO,eAAe,CAAC,KAAK,CAAC;QACjC,CAAC;IACH,CAAC,CAAC","sourcesContent":["import { wrapPromiseWithState } from \"../../../utilities/index.js\";\nimport * as React from \"rehackt\";\n\ntype Use = <T>(promise: Promise<T>) => T;\n// Prevent webpack from complaining about our feature detection of the\n// use property of the React namespace, which is expected not\n// to exist when using current stable versions, and that's fine.\nconst useKey = \"use\" as keyof typeof React;\nconst realHook = React[useKey] as Use | undefined;\n\n// This is named with two underscores to allow this hook to evade typical rules of\n// hooks (i.e. it can be used conditionally)\nexport const __use =\n realHook ||\n function __use<TValue>(promise: Promise<TValue>) {\n const statefulPromise = wrapPromiseWithState(promise);\n\n switch (statefulPromise.status) {\n case \"pending\":\n throw statefulPromise;\n case \"rejected\":\n throw statefulPromise.reason;\n case \"fulfilled\":\n return statefulPromise.value;\n }\n };\n"]}

View File

@@ -0,0 +1,6 @@
export { useDeepMemo } from "./useDeepMemo.js";
export { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect.js";
export { useRenderGuard } from "./useRenderGuard.js";
export { useLazyRef } from "./useLazyRef.js";
export { __use } from "./__use.js";
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1,7 @@
// These hooks are used internally and are not exported publicly by the library
export { useDeepMemo } from "./useDeepMemo.js";
export { useIsomorphicLayoutEffect } from "./useIsomorphicLayoutEffect.js";
export { useRenderGuard } from "./useRenderGuard.js";
export { useLazyRef } from "./useLazyRef.js";
export { __use } from "./__use.js";
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC","sourcesContent":["// These hooks are used internally and are not exported publicly by the library\nexport { useDeepMemo } from \"./useDeepMemo.js\";\nexport { useIsomorphicLayoutEffect } from \"./useIsomorphicLayoutEffect.js\";\nexport { useRenderGuard } from \"./useRenderGuard.js\";\nexport { useLazyRef } from \"./useLazyRef.js\";\nexport { __use } from \"./__use.js\";\n"]}

View File

@@ -0,0 +1,3 @@
import type { DependencyList } from "react";
export declare function useDeepMemo<TValue>(memoFn: () => TValue, deps: DependencyList): TValue;
//# sourceMappingURL=useDeepMemo.d.ts.map

View File

@@ -0,0 +1,10 @@
import * as React from "rehackt";
import { equal } from "@wry/equality";
export function useDeepMemo(memoFn, deps) {
var ref = React.useRef();
if (!ref.current || !equal(ref.current.deps, deps)) {
ref.current = { value: memoFn(), deps: deps };
}
return ref.current.value;
}
//# sourceMappingURL=useDeepMemo.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useDeepMemo.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/useDeepMemo.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAEtC,MAAM,UAAU,WAAW,CACzB,MAAoB,EACpB,IAAoB;IAEpB,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,EAA2C,CAAC;IAEpE,IAAI,CAAC,GAAG,CAAC,OAAO,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,EAAE,CAAC;QACnD,GAAG,CAAC,OAAO,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,IAAI,MAAA,EAAE,CAAC;IAC1C,CAAC;IAED,OAAO,GAAG,CAAC,OAAO,CAAC,KAAK,CAAC;AAC3B,CAAC","sourcesContent":["import type { DependencyList } from \"react\";\nimport * as React from \"rehackt\";\nimport { equal } from \"@wry/equality\";\n\nexport function useDeepMemo<TValue>(\n memoFn: () => TValue,\n deps: DependencyList\n) {\n const ref = React.useRef<{ deps: DependencyList; value: TValue }>();\n\n if (!ref.current || !equal(ref.current.deps, deps)) {\n ref.current = { value: memoFn(), deps };\n }\n\n return ref.current.value;\n}\n"]}

View File

@@ -0,0 +1,4 @@
/// <reference types="react" />
import * as React from "rehackt";
export declare const useIsomorphicLayoutEffect: typeof React.useLayoutEffect;
//# sourceMappingURL=useIsomorphicLayoutEffect.d.ts.map

View File

@@ -0,0 +1,9 @@
import * as React from "rehackt";
import { canUseDOM } from "../../../utilities/index.js";
// use canUseDOM here instead of canUseLayoutEffect because we want to be able
// to use useLayoutEffect in our jest tests. useLayoutEffect seems to work fine
// in useSuspenseQuery tests, but to honor the original comment about the
// warnings for useSyncExternalStore implementation, canUseLayoutEffect is left
// alone.
export var useIsomorphicLayoutEffect = canUseDOM ? React.useLayoutEffect : React.useEffect;
//# sourceMappingURL=useIsomorphicLayoutEffect.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useIsomorphicLayoutEffect.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/useIsomorphicLayoutEffect.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,SAAS,EAAE,MAAM,6BAA6B,CAAC;AAExD,8EAA8E;AAC9E,+EAA+E;AAC/E,yEAAyE;AACzE,+EAA+E;AAC/E,SAAS;AACT,MAAM,CAAC,IAAM,yBAAyB,GACpC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC","sourcesContent":["import * as React from \"rehackt\";\nimport { canUseDOM } from \"../../../utilities/index.js\";\n\n// use canUseDOM here instead of canUseLayoutEffect because we want to be able\n// to use useLayoutEffect in our jest tests. useLayoutEffect seems to work fine\n// in useSuspenseQuery tests, but to honor the original comment about the\n// warnings for useSyncExternalStore implementation, canUseLayoutEffect is left\n// alone.\nexport const useIsomorphicLayoutEffect =\n canUseDOM ? React.useLayoutEffect : React.useEffect;\n"]}

View File

@@ -0,0 +1,4 @@
/// <reference types="react" />
import * as React from "rehackt";
export declare function useLazyRef<T>(getInitialValue: () => T): React.MutableRefObject<T>;
//# sourceMappingURL=useLazyRef.d.ts.map

View File

@@ -0,0 +1,10 @@
import * as React from "rehackt";
var INIT = {};
export function useLazyRef(getInitialValue) {
var ref = React.useRef(INIT);
if (ref.current === INIT) {
ref.current = getInitialValue();
}
return ref;
}
//# sourceMappingURL=useLazyRef.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useLazyRef.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/useLazyRef.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC,IAAM,IAAI,GAAG,EAAE,CAAC;AAEhB,MAAM,UAAU,UAAU,CAAI,eAAwB;IACpD,IAAM,GAAG,GAAG,KAAK,CAAC,MAAM,CAAI,IAAoB,CAAC,CAAC;IAElD,IAAI,GAAG,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;QACzB,GAAG,CAAC,OAAO,GAAG,eAAe,EAAE,CAAC;IAClC,CAAC;IAED,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["import * as React from \"rehackt\";\n\nconst INIT = {};\n\nexport function useLazyRef<T>(getInitialValue: () => T) {\n const ref = React.useRef<T>(INIT as unknown as T);\n\n if (ref.current === INIT) {\n ref.current = getInitialValue();\n }\n\n return ref;\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare function useRenderGuard(): () => boolean;
//# sourceMappingURL=useRenderGuard.d.ts.map

View File

@@ -0,0 +1,17 @@
import * as React from "rehackt";
function getRenderDispatcher() {
var _a, _b;
return (_b = (_a = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED) === null || _a === void 0 ? void 0 : _a.ReactCurrentDispatcher) === null || _b === void 0 ? void 0 : _b.current;
}
var RenderDispatcher = null;
/*
Relay does this too, so we hope this is safe.
https://github.com/facebook/relay/blob/8651fbca19adbfbb79af7a3bc40834d105fd7747/packages/react-relay/relay-hooks/loadQuery.js#L90-L98
*/
export function useRenderGuard() {
RenderDispatcher = getRenderDispatcher();
return React.useCallback(function () {
return (RenderDispatcher !== null && RenderDispatcher === getRenderDispatcher());
}, []);
}
//# sourceMappingURL=useRenderGuard.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useRenderGuard.js","sourceRoot":"","sources":["../../../../src/react/hooks/internal/useRenderGuard.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC,SAAS,mBAAmB;;IAC1B,OAAO,MAAA,MAAC,KAAa,CAAC,kDAAkD,0CACpE,sBAAsB,0CAAE,OAAO,CAAC;AACtC,CAAC;AAED,IAAI,gBAAgB,GAAY,IAAI,CAAC;AAErC;;;EAGE;AACF,MAAM,UAAU,cAAc;IAC5B,gBAAgB,GAAG,mBAAmB,EAAE,CAAC;IAEzC,OAAO,KAAK,CAAC,WAAW,CAAC;QACvB,OAAO,CACL,gBAAgB,KAAK,IAAI,IAAI,gBAAgB,KAAK,mBAAmB,EAAE,CACxE,CAAC;IACJ,CAAC,EAAE,EAAE,CAAC,CAAC;AACT,CAAC","sourcesContent":["import * as React from \"rehackt\";\n\nfunction getRenderDispatcher() {\n return (React as any).__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED\n ?.ReactCurrentDispatcher?.current;\n}\n\nlet RenderDispatcher: unknown = null;\n\n/*\nRelay does this too, so we hope this is safe.\nhttps://github.com/facebook/relay/blob/8651fbca19adbfbb79af7a3bc40834d105fd7747/packages/react-relay/relay-hooks/loadQuery.js#L90-L98\n*/\nexport function useRenderGuard() {\n RenderDispatcher = getRenderDispatcher();\n\n return React.useCallback(() => {\n return (\n RenderDispatcher !== null && RenderDispatcher === getRenderDispatcher()\n );\n }, []);\n}\n"]}

View File

@@ -0,0 +1,8 @@
{
"name": "@apollo/client/react/hooks",
"type": "module",
"main": "hooks.cjs",
"module": "index.js",
"types": "index.d.ts",
"sideEffects": false
}

View File

@@ -0,0 +1,18 @@
import type { ApolloClient } from "../../core/index.js";
/**
* @example
* ```jsx
* import { useApolloClient } from '@apollo/client';
*
* function SomeComponent() {
* const client = useApolloClient();
* // `client` is now set to the `ApolloClient` instance being used by the
* // application (that was configured using something like `ApolloProvider`)
* }
* ```
*
* @since 3.0.0
* @returns The `ApolloClient` instance being used by the application.
*/
export declare function useApolloClient(override?: ApolloClient<object>): ApolloClient<object>;
//# sourceMappingURL=useApolloClient.d.ts.map

View File

@@ -0,0 +1,25 @@
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { getApolloContext } from "../context/index.js";
/**
* @example
* ```jsx
* import { useApolloClient } from '@apollo/client';
*
* function SomeComponent() {
* const client = useApolloClient();
* // `client` is now set to the `ApolloClient` instance being used by the
* // application (that was configured using something like `ApolloProvider`)
* }
* ```
*
* @since 3.0.0
* @returns The `ApolloClient` instance being used by the application.
*/
export function useApolloClient(override) {
var context = React.useContext(getApolloContext());
var client = override || context.client;
invariant(!!client, 49);
return client;
}
//# sourceMappingURL=useApolloClient.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useApolloClient.js","sourceRoot":"","sources":["../../../src/react/hooks/useApolloClient.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,kCAAkC,CAAC;AAC7D,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAEvD;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA+B;IAE/B,IAAM,OAAO,GAAG,KAAK,CAAC,UAAU,CAAC,gBAAgB,EAAE,CAAC,CAAC;IACrD,IAAM,MAAM,GAAG,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAC1C,SAAS,CACP,CAAC,CAAC,MAAM,EACR,oEAAoE;QAClE,0EAA0E;QAC1E,0BAA0B,CAC7B,CAAC;IAEF,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { invariant } from \"../../utilities/globals/index.js\";\nimport * as React from \"rehackt\";\nimport type { ApolloClient } from \"../../core/index.js\";\nimport { getApolloContext } from \"../context/index.js\";\n\n/**\n * @example\n * ```jsx\n * import { useApolloClient } from '@apollo/client';\n *\n * function SomeComponent() {\n * const client = useApolloClient();\n * // `client` is now set to the `ApolloClient` instance being used by the\n * // application (that was configured using something like `ApolloProvider`)\n * }\n * ```\n *\n * @since 3.0.0\n * @returns The `ApolloClient` instance being used by the application.\n */\nexport function useApolloClient(\n override?: ApolloClient<object>\n): ApolloClient<object> {\n const context = React.useContext(getApolloContext());\n const client = override || context.client;\n invariant(\n !!client,\n 'Could not find \"client\" in the context or passed in as an option. ' +\n \"Wrap the root component in an <ApolloProvider>, or pass an ApolloClient \" +\n \"instance in via options.\"\n );\n\n return client;\n}\n"]}

View File

@@ -0,0 +1,64 @@
import type { DocumentNode, OperationVariables, TypedDocumentNode } from "../../core/index.js";
import type { QueryReference } from "../internal/index.js";
import type { BackgroundQueryHookOptions, NoInfer } from "../types/types.js";
import type { FetchMoreFunction, RefetchFunction } from "./useSuspenseQuery.js";
import type { DeepPartial } from "../../utilities/index.js";
import type { SkipToken } from "./constants.js";
export type UseBackgroundQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = {
fetchMore: FetchMoreFunction<TData, TVariables>;
refetch: RefetchFunction<TData, TVariables>;
};
type BackgroundQueryHookOptionsNoInfer<TData, TVariables extends OperationVariables> = BackgroundQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>;
export declare function useBackgroundQuery<TData, TVariables extends OperationVariables, TOptions extends Omit<BackgroundQueryHookOptions<TData>, "variables">>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & TOptions): [
(QueryReference<TOptions["errorPolicy"] extends "ignore" | "all" ? TOptions["returnPartialData"] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions["returnPartialData"] extends true ? DeepPartial<TData> : TData, TVariables> | (TOptions["skip"] extends boolean ? undefined : never)),
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
returnPartialData: true;
errorPolicy: "ignore" | "all";
}): [
QueryReference<DeepPartial<TData> | undefined, TVariables>,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
errorPolicy: "ignore" | "all";
}): [
QueryReference<TData | undefined, TVariables>,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
skip: boolean;
returnPartialData: true;
}): [
QueryReference<DeepPartial<TData>, TVariables> | undefined,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
returnPartialData: true;
}): [
QueryReference<DeepPartial<TData>, TVariables>,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
skip: boolean;
}): [
QueryReference<TData, TVariables> | undefined,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: BackgroundQueryHookOptionsNoInfer<TData, TVariables>): [
QueryReference<TData, TVariables>,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SkipToken): [undefined, UseBackgroundQueryResult<TData, TVariables>];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SkipToken | (BackgroundQueryHookOptionsNoInfer<TData, TVariables> & {
returnPartialData: true;
})): [
QueryReference<DeepPartial<TData>, TVariables> | undefined,
UseBackgroundQueryResult<TData, TVariables>
];
export declare function useBackgroundQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SkipToken | BackgroundQueryHookOptionsNoInfer<TData, TVariables>): [
QueryReference<TData, TVariables> | undefined,
UseBackgroundQueryResult<TData, TVariables>
];
export {};
//# sourceMappingURL=useBackgroundQuery.d.ts.map

View File

@@ -0,0 +1,52 @@
import { __spreadArray } from "tslib";
import * as React from "rehackt";
import { useApolloClient } from "./useApolloClient.js";
import { getSuspenseCache, unwrapQueryRef, updateWrappedQueryRef, wrapQueryRef, } from "../internal/index.js";
import { useWatchQueryOptions } from "./useSuspenseQuery.js";
import { canonicalStringify } from "../../cache/index.js";
export function useBackgroundQuery(query, options) {
if (options === void 0) { options = Object.create(null); }
var client = useApolloClient(options.client);
var suspenseCache = getSuspenseCache(client);
var watchQueryOptions = useWatchQueryOptions({ client: client, query: query, options: options });
var fetchPolicy = watchQueryOptions.fetchPolicy, variables = watchQueryOptions.variables;
var _a = options.queryKey, queryKey = _a === void 0 ? [] : _a;
// This ref tracks the first time query execution is enabled to determine
// whether to return a query ref or `undefined`. When initialized
// in a skipped state (either via `skip: true` or `skipToken`) we return
// `undefined` for the `queryRef` until the query has been enabled. Once
// enabled, a query ref is always returned regardless of whether the query is
// skipped again later.
var didFetchResult = React.useRef(fetchPolicy !== "standby");
didFetchResult.current || (didFetchResult.current = fetchPolicy !== "standby");
var cacheKey = __spreadArray([
query,
canonicalStringify(variables)
], [].concat(queryKey), true);
var queryRef = suspenseCache.getQueryRef(cacheKey, function () {
return client.watchQuery(watchQueryOptions);
});
var _b = React.useState(wrapQueryRef(queryRef)), wrappedQueryRef = _b[0], setWrappedQueryRef = _b[1];
if (unwrapQueryRef(wrappedQueryRef) !== queryRef) {
setWrappedQueryRef(wrapQueryRef(queryRef));
}
if (queryRef.didChangeOptions(watchQueryOptions)) {
var promise = queryRef.applyOptions(watchQueryOptions);
updateWrappedQueryRef(wrappedQueryRef, promise);
}
var fetchMore = React.useCallback(function (options) {
var promise = queryRef.fetchMore(options);
setWrappedQueryRef(wrapQueryRef(queryRef));
return promise;
}, [queryRef]);
var refetch = React.useCallback(function (variables) {
var promise = queryRef.refetch(variables);
setWrappedQueryRef(wrapQueryRef(queryRef));
return promise;
}, [queryRef]);
return [
didFetchResult.current ? wrappedQueryRef : void 0,
{ fetchMore: fetchMore, refetch: refetch },
];
}
//# sourceMappingURL=useBackgroundQuery.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,28 @@
import type { DeepPartial } from "../../utilities/index.js";
import type { Cache, Reference, StoreObject, MissingTree } from "../../cache/index.js";
import type { ApolloClient, OperationVariables } from "../../core/index.js";
import type { NoInfer } from "../types/types.js";
export interface UseFragmentOptions<TData, TVars> extends Omit<Cache.DiffOptions<NoInfer<TData>, NoInfer<TVars>>, "id" | "query" | "optimistic" | "previousResult" | "returnPartialData">, Omit<Cache.ReadFragmentOptions<TData, TVars>, "id" | "variables" | "returnPartialData"> {
from: StoreObject | Reference | string;
optimistic?: boolean;
/**
* The instance of {@link ApolloClient} to use to look up the fragment.
*
* By default, the instance that's passed down via context is used, but you
* can provide a different instance here.
*
* @docGroup 1. Operation options
*/
client?: ApolloClient<any>;
}
export type UseFragmentResult<TData> = {
data: TData;
complete: true;
missing?: never;
} | {
data: DeepPartial<TData>;
complete: false;
missing?: MissingTree;
};
export declare function useFragment<TData = any, TVars = OperationVariables>(options: UseFragmentOptions<TData, TVars>): UseFragmentResult<TData>;
//# sourceMappingURL=useFragment.d.ts.map

View File

@@ -0,0 +1,48 @@
import { __assign, __rest } from "tslib";
import * as React from "rehackt";
import { equal } from "@wry/equality";
import { mergeDeepArray } from "../../utilities/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import { useDeepMemo, useLazyRef } from "./internal/index.js";
export function useFragment(options) {
var cache = useApolloClient(options.client).cache;
var diffOptions = useDeepMemo(function () {
var fragment = options.fragment, fragmentName = options.fragmentName, from = options.from, _a = options.optimistic, optimistic = _a === void 0 ? true : _a, rest = __rest(options, ["fragment", "fragmentName", "from", "optimistic"]);
return __assign(__assign({}, rest), { returnPartialData: true, id: typeof from === "string" ? from : cache.identify(from), query: cache["getFragmentDoc"](fragment, fragmentName), optimistic: optimistic });
}, [options]);
var resultRef = useLazyRef(function () {
return diffToResult(cache.diff(diffOptions));
});
// Used for both getSnapshot and getServerSnapshot
var getSnapshot = React.useCallback(function () { return resultRef.current; }, []);
return useSyncExternalStore(React.useCallback(function (forceUpdate) {
var lastTimeout = 0;
var unsubscribe = cache.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {
if (!equal(diff.result, resultRef.current.data)) {
resultRef.current = diffToResult(diff);
// If we get another update before we've re-rendered, bail out of
// the update and try again. This ensures that the relative timing
// between useQuery and useFragment stays roughly the same as
// fixed in https://github.com/apollographql/apollo-client/pull/11083
clearTimeout(lastTimeout);
lastTimeout = setTimeout(forceUpdate);
}
} }));
return function () {
unsubscribe();
clearTimeout(lastTimeout);
};
}, [cache, diffOptions]), getSnapshot, getSnapshot);
}
function diffToResult(diff) {
var result = {
data: diff.result,
complete: !!diff.complete,
};
if (diff.missing) {
result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
}
return result;
}
//# sourceMappingURL=useFragment.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,41 @@
import type { DocumentNode } from "graphql";
import type { TypedDocumentNode } from "@graphql-typed-document-node/core";
import type { OperationVariables } from "../../core/index.js";
import type { LazyQueryHookOptions, LazyQueryResultTuple, NoInfer } from "../types/types.js";
/**
* A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.
*
* > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.
*
* @example
* ```jsx
* import { gql, useLazyQuery } from "@apollo/client";
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const [loadGreeting, { called, loading, data }] = useLazyQuery(
* GET_GREETING,
* { variables: { language: "english" } }
* );
* if (called && loading) return <p>Loading ...</p>
* if (!called) {
* return <button onClick={() => loadGreeting()}>Load greeting</button>
* }
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
* @since 3.0.0
*
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Default options to control how the query is executed.
* @returns A tuple in the form of `[execute, result]`
*/
export declare function useLazyQuery<TData = any, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: LazyQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>): LazyQueryResultTuple<TData, TVariables>;
//# sourceMappingURL=useLazyQuery.d.ts.map

View File

@@ -0,0 +1,107 @@
import { __assign } from "tslib";
import * as React from "rehackt";
import { mergeOptions } from "../../utilities/index.js";
import { useInternalState } from "./useQuery.js";
import { useApolloClient } from "./useApolloClient.js";
// The following methods, when called will execute the query, regardless of
// whether the useLazyQuery execute function was called before.
var EAGER_METHODS = [
"refetch",
"reobserve",
"fetchMore",
"updateQuery",
"startPolling",
"subscribeToMore",
];
/**
* A hook for imperatively executing queries in an Apollo application, e.g. in response to user interaction.
*
* > Refer to the [Queries - Manual execution with useLazyQuery](https://www.apollographql.com/docs/react/data/queries#manual-execution-with-uselazyquery) section for a more in-depth overview of `useLazyQuery`.
*
* @example
* ```jsx
* import { gql, useLazyQuery } from "@apollo/client";
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const [loadGreeting, { called, loading, data }] = useLazyQuery(
* GET_GREETING,
* { variables: { language: "english" } }
* );
* if (called && loading) return <p>Loading ...</p>
* if (!called) {
* return <button onClick={() => loadGreeting()}>Load greeting</button>
* }
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
* @since 3.0.0
*
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Default options to control how the query is executed.
* @returns A tuple in the form of `[execute, result]`
*/
export function useLazyQuery(query, options) {
var _a;
var execOptionsRef = React.useRef();
var optionsRef = React.useRef();
var queryRef = React.useRef();
var merged = mergeOptions(options, execOptionsRef.current || {});
var document = (_a = merged === null || merged === void 0 ? void 0 : merged.query) !== null && _a !== void 0 ? _a : query;
// Use refs to track options and the used query to ensure the `execute`
// function remains referentially stable between renders.
optionsRef.current = options;
queryRef.current = document;
var internalState = useInternalState(useApolloClient(options && options.client), document);
var useQueryResult = internalState.useQuery(__assign(__assign({}, merged), { skip: !execOptionsRef.current }));
var initialFetchPolicy = useQueryResult.observable.options.initialFetchPolicy ||
internalState.getDefaultFetchPolicy();
var result = Object.assign(useQueryResult, {
called: !!execOptionsRef.current,
});
// We use useMemo here to make sure the eager methods have a stable identity.
var eagerMethods = React.useMemo(function () {
var eagerMethods = {};
var _loop_1 = function (key) {
var method = result[key];
eagerMethods[key] = function () {
if (!execOptionsRef.current) {
execOptionsRef.current = Object.create(null);
// Only the first time populating execOptionsRef.current matters here.
internalState.forceUpdateState();
}
// @ts-expect-error this is just too generic to type
return method.apply(this, arguments);
};
};
for (var _i = 0, EAGER_METHODS_1 = EAGER_METHODS; _i < EAGER_METHODS_1.length; _i++) {
var key = EAGER_METHODS_1[_i];
_loop_1(key);
}
return eagerMethods;
}, []);
Object.assign(result, eagerMethods);
var execute = React.useCallback(function (executeOptions) {
execOptionsRef.current =
executeOptions ? __assign(__assign({}, executeOptions), { fetchPolicy: executeOptions.fetchPolicy || initialFetchPolicy }) : {
fetchPolicy: initialFetchPolicy,
};
var options = mergeOptions(optionsRef.current, __assign({ query: queryRef.current }, execOptionsRef.current));
var promise = internalState
.executeQuery(__assign(__assign({}, options), { skip: false }))
.then(function (queryResult) { return Object.assign(queryResult, eagerMethods); });
// Because the return value of `useLazyQuery` is usually floated, we need
// to catch the promise to prevent unhandled rejections.
promise.catch(function () { });
return promise;
}, []);
return [execute, result];
}
//# sourceMappingURL=useLazyQuery.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,97 @@
import type { DocumentNode, OperationVariables, TypedDocumentNode } from "../../core/index.js";
import type { QueryReference } from "../internal/index.js";
import type { LoadableQueryHookOptions } from "../types/types.js";
import type { FetchMoreFunction, RefetchFunction } from "./useSuspenseQuery.js";
import type { DeepPartial, OnlyRequiredProperties } from "../../utilities/index.js";
export type LoadQueryFunction<TVariables extends OperationVariables> = (...args: [TVariables] extends [never] ? [] : {} extends OnlyRequiredProperties<TVariables> ? [variables?: TVariables] : [variables: TVariables]) => void;
type ResetFunction = () => void;
export type UseLoadableQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> = [
loadQuery: LoadQueryFunction<TVariables>,
queryRef: QueryReference<TData, TVariables> | null,
{
/**
* A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
*
*
* @docGroup
*
* 3. Helper functions
*/
fetchMore: FetchMoreFunction<TData, TVariables>;
/**
* A function that enables you to re-execute the query, optionally passing in new `variables`.
*
* To guarantee that the refetch performs a network request, its `fetchPolicy` is set to `network-only` (unless the original query's `fetchPolicy` is `no-cache` or `cache-and-network`, which also guarantee a network request).
*
* See also [Refetching](https://www.apollographql.com/docs/react/data/queries/#refetching).
*
* @docGroup
*
* 3. Helper functions
*/
refetch: RefetchFunction<TData, TVariables>;
/**
* A function that resets the `queryRef` back to `null`.
*/
reset: ResetFunction;
}
];
export declare function useLoadableQuery<TData, TVariables extends OperationVariables, TOptions extends LoadableQueryHookOptions>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: LoadableQueryHookOptions & TOptions): UseLoadableQueryResult<TOptions["errorPolicy"] extends "ignore" | "all" ? TOptions["returnPartialData"] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions["returnPartialData"] extends true ? DeepPartial<TData> : TData, TVariables>;
export declare function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: LoadableQueryHookOptions & {
returnPartialData: true;
errorPolicy: "ignore" | "all";
}): UseLoadableQueryResult<DeepPartial<TData> | undefined, TVariables>;
export declare function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: LoadableQueryHookOptions & {
errorPolicy: "ignore" | "all";
}): UseLoadableQueryResult<TData | undefined, TVariables>;
export declare function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: LoadableQueryHookOptions & {
returnPartialData: true;
}): UseLoadableQueryResult<DeepPartial<TData>, TVariables>;
/**
* A hook for imperatively loading a query, such as responding to a user
* interaction.
*
* > Refer to the [Suspense - Fetching in response to user interaction](https://www.apollographql.com/docs/react/data/suspense#fetching-in-response-to-user-interaction) section for a more in-depth overview of `useLoadableQuery`.
*
* @example
* ```jsx
* import { gql, useLoadableQuery } from "@apollo/client";
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function App() {
* const [loadGreeting, queryRef] = useLoadableQuery(GET_GREETING);
*
* return (
* <>
* <button onClick={() => loadGreeting({ language: "english" })}>
* Load greeting
* </button>
* <Suspense fallback={<div>Loading...</div>}>
* {queryRef && <Hello queryRef={queryRef} />}
* </Suspense>
* </>
* );
* }
*
* function Hello({ queryRef }) {
* const { data } = useReadQuery(queryRef);
*
* return <div>{data.greeting.message}</div>;
* }
* ```
*
* @since 3.9.0
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Options to control how the query is executed.
* @returns A tuple in the form of `[loadQuery, queryRef, handlers]`
*/
export declare function useLoadableQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: LoadableQueryHookOptions): UseLoadableQueryResult<TData, TVariables>;
export {};
//# sourceMappingURL=useLoadableQuery.d.ts.map

View File

@@ -0,0 +1,59 @@
import { __assign, __spreadArray } from "tslib";
import * as React from "rehackt";
import { useApolloClient } from "./useApolloClient.js";
import { getSuspenseCache, unwrapQueryRef, updateWrappedQueryRef, wrapQueryRef, } from "../internal/index.js";
import { useRenderGuard } from "./internal/index.js";
import { useWatchQueryOptions } from "./useSuspenseQuery.js";
import { canonicalStringify } from "../../cache/index.js";
import { invariant } from "../../utilities/globals/index.js";
export function useLoadableQuery(query, options) {
if (options === void 0) { options = Object.create(null); }
var client = useApolloClient(options.client);
var suspenseCache = getSuspenseCache(client);
var watchQueryOptions = useWatchQueryOptions({ client: client, query: query, options: options });
var _a = options.queryKey, queryKey = _a === void 0 ? [] : _a;
var _b = React.useState(null), queryRef = _b[0], setQueryRef = _b[1];
var internalQueryRef = queryRef && unwrapQueryRef(queryRef);
if (queryRef && (internalQueryRef === null || internalQueryRef === void 0 ? void 0 : internalQueryRef.didChangeOptions(watchQueryOptions))) {
var promise = internalQueryRef.applyOptions(watchQueryOptions);
updateWrappedQueryRef(queryRef, promise);
}
var calledDuringRender = useRenderGuard();
var fetchMore = React.useCallback(function (options) {
if (!internalQueryRef) {
throw new Error("The query has not been loaded. Please load the query.");
}
var promise = internalQueryRef.fetchMore(options);
setQueryRef(wrapQueryRef(internalQueryRef));
return promise;
}, [internalQueryRef]);
var refetch = React.useCallback(function (options) {
if (!internalQueryRef) {
throw new Error("The query has not been loaded. Please load the query.");
}
var promise = internalQueryRef.refetch(options);
setQueryRef(wrapQueryRef(internalQueryRef));
return promise;
}, [internalQueryRef]);
var loadQuery = React.useCallback(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
invariant(!calledDuringRender(), 50);
var variables = args[0];
var cacheKey = __spreadArray([
query,
canonicalStringify(variables)
], [].concat(queryKey), true);
var queryRef = suspenseCache.getQueryRef(cacheKey, function () {
return client.watchQuery(__assign(__assign({}, watchQueryOptions), { variables: variables }));
});
setQueryRef(wrapQueryRef(queryRef));
}, [query, queryKey, suspenseCache, watchQueryOptions, calledDuringRender]);
var reset = React.useCallback(function () {
setQueryRef(null);
}, [queryRef]);
return [loadQuery, queryRef, { fetchMore: fetchMore, refetch: refetch, reset: reset }];
}
//# sourceMappingURL=useLoadableQuery.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,53 @@
import type { DocumentNode } from "graphql";
import type { TypedDocumentNode } from "@graphql-typed-document-node/core";
import type { MutationHookOptions, MutationTuple, NoInfer } from "../types/types.js";
import type { ApolloCache, DefaultContext, OperationVariables } from "../../core/index.js";
/**
*
*
* > Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of `useMutation`.
*
* @example
* ```jsx
* import { gql, useMutation } from '@apollo/client';
*
* const ADD_TODO = gql`
* mutation AddTodo($type: String!) {
* addTodo(type: $type) {
* id
* type
* }
* }
* `;
*
* function AddTodo() {
* let input;
* const [addTodo, { data }] = useMutation(ADD_TODO);
*
* return (
* <div>
* <form
* onSubmit={e => {
* e.preventDefault();
* addTodo({ variables: { type: input.value } });
* input.value = '';
* }}
* >
* <input
* ref={node => {
* input = node;
* }}
* />
* <button type="submit">Add Todo</button>
* </form>
* </div>
* );
* }
* ```
* @since 3.0.0
* @param mutation - A GraphQL mutation document parsed into an AST by `gql`.
* @param options - Options to control how the mutation is executed.
* @returns A tuple in the form of `[mutate, result]`
*/
export declare function useMutation<TData = any, TVariables = OperationVariables, TContext = DefaultContext, TCache extends ApolloCache<any> = ApolloCache<any>>(mutation: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: MutationHookOptions<NoInfer<TData>, NoInfer<TVariables>, TContext, TCache>): MutationTuple<TData, TVariables, TContext, TCache>;
//# sourceMappingURL=useMutation.d.ts.map

View File

@@ -0,0 +1,163 @@
import { __assign } from "tslib";
import * as React from "rehackt";
import { mergeOptions } from "../../utilities/index.js";
import { equal } from "@wry/equality";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { ApolloError } from "../../errors/index.js";
import { useApolloClient } from "./useApolloClient.js";
/**
*
*
* > Refer to the [Mutations](https://www.apollographql.com/docs/react/data/mutations/) section for a more in-depth overview of `useMutation`.
*
* @example
* ```jsx
* import { gql, useMutation } from '@apollo/client';
*
* const ADD_TODO = gql`
* mutation AddTodo($type: String!) {
* addTodo(type: $type) {
* id
* type
* }
* }
* `;
*
* function AddTodo() {
* let input;
* const [addTodo, { data }] = useMutation(ADD_TODO);
*
* return (
* <div>
* <form
* onSubmit={e => {
* e.preventDefault();
* addTodo({ variables: { type: input.value } });
* input.value = '';
* }}
* >
* <input
* ref={node => {
* input = node;
* }}
* />
* <button type="submit">Add Todo</button>
* </form>
* </div>
* );
* }
* ```
* @since 3.0.0
* @param mutation - A GraphQL mutation document parsed into an AST by `gql`.
* @param options - Options to control how the mutation is executed.
* @returns A tuple in the form of `[mutate, result]`
*/
export function useMutation(mutation, options) {
var client = useApolloClient(options === null || options === void 0 ? void 0 : options.client);
verifyDocumentType(mutation, DocumentType.Mutation);
var _a = React.useState({
called: false,
loading: false,
client: client,
}), result = _a[0], setResult = _a[1];
var ref = React.useRef({
result: result,
mutationId: 0,
isMounted: true,
client: client,
mutation: mutation,
options: options,
});
// TODO: Trying to assign these in a useEffect or useLayoutEffect breaks
// higher-order components.
{
Object.assign(ref.current, { client: client, options: options, mutation: mutation });
}
var execute = React.useCallback(function (executeOptions) {
if (executeOptions === void 0) { executeOptions = {}; }
var _a = ref.current, options = _a.options, mutation = _a.mutation;
var baseOptions = __assign(__assign({}, options), { mutation: mutation });
var client = executeOptions.client || ref.current.client;
if (!ref.current.result.loading &&
!baseOptions.ignoreResults &&
ref.current.isMounted) {
setResult((ref.current.result = {
loading: true,
error: void 0,
data: void 0,
called: true,
client: client,
}));
}
var mutationId = ++ref.current.mutationId;
var clientOptions = mergeOptions(baseOptions, executeOptions);
return client
.mutate(clientOptions)
.then(function (response) {
var _a, _b;
var data = response.data, errors = response.errors;
var error = errors && errors.length > 0 ?
new ApolloError({ graphQLErrors: errors })
: void 0;
var onError = executeOptions.onError || ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError);
if (error && onError) {
onError(error, clientOptions);
}
if (mutationId === ref.current.mutationId &&
!clientOptions.ignoreResults) {
var result_1 = {
called: true,
loading: false,
data: data,
error: error,
client: client,
};
if (ref.current.isMounted && !equal(ref.current.result, result_1)) {
setResult((ref.current.result = result_1));
}
}
var onCompleted = executeOptions.onCompleted || ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onCompleted);
if (!error) {
onCompleted === null || onCompleted === void 0 ? void 0 : onCompleted(response.data, clientOptions);
}
return response;
})
.catch(function (error) {
var _a;
if (mutationId === ref.current.mutationId && ref.current.isMounted) {
var result_2 = {
loading: false,
error: error,
data: void 0,
called: true,
client: client,
};
if (!equal(ref.current.result, result_2)) {
setResult((ref.current.result = result_2));
}
}
var onError = executeOptions.onError || ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError);
if (onError) {
onError(error, clientOptions);
// TODO(brian): why are we returning this here???
return { data: void 0, errors: error };
}
throw error;
});
}, []);
var reset = React.useCallback(function () {
if (ref.current.isMounted) {
var result_3 = { called: false, loading: false, client: client };
Object.assign(ref.current, { mutationId: 0, result: result_3 });
setResult(result_3);
}
}, []);
React.useEffect(function () {
ref.current.isMounted = true;
return function () {
ref.current.isMounted = false;
};
}, []);
return [execute, __assign({ reset: reset }, result)];
}
//# sourceMappingURL=useMutation.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,87 @@
import type { OperationVariables, WatchQueryFetchPolicy } from "../../core/index.js";
import type { ApolloClient, ApolloQueryResult, DocumentNode, TypedDocumentNode } from "../../core/index.js";
import type { QueryHookOptions, QueryResult, NoInfer } from "../types/types.js";
import { useApolloClient } from "./useApolloClient.js";
/**
* A hook for executing queries in an Apollo application.
*
* To run a query within a React component, call `useQuery` and pass it a GraphQL query document.
*
* When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.
*
* > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.
*
* @example
* ```jsx
* import { gql, useQuery } from '@apollo/client';
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const { loading, error, data } = useQuery(GET_GREETING, {
* variables: { language: 'english' },
* });
* if (loading) return <p>Loading ...</p>;
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
* @since 3.0.0
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Options to control how the query is executed.
* @returns Query result object
*/
export declare function useQuery<TData = any, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: QueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>): QueryResult<TData, TVariables>;
export declare function useInternalState<TData, TVariables extends OperationVariables>(client: ApolloClient<any>, query: DocumentNode | TypedDocumentNode<TData, TVariables>): InternalState<TData, TVariables>;
declare class InternalState<TData, TVariables extends OperationVariables> {
readonly client: ReturnType<typeof useApolloClient>;
readonly query: DocumentNode | TypedDocumentNode<TData, TVariables>;
constructor(client: ReturnType<typeof useApolloClient>, query: DocumentNode | TypedDocumentNode<TData, TVariables>, previous?: InternalState<TData, TVariables>);
/**
* Forces an update using local component state.
* As this is not batched with `useSyncExternalStore` updates,
* this is only used as a fallback if the `useSyncExternalStore` "force update"
* method is not registered at the moment.
* See https://github.com/facebook/react/issues/25191
* */
forceUpdateState(): void;
/**
* Will be overwritten by the `useSyncExternalStore` "force update" method
* whenever it is available and reset to `forceUpdateState` when it isn't.
*/
forceUpdate: () => void;
executeQuery(options: QueryHookOptions<TData, TVariables> & {
query?: DocumentNode;
}): Promise<QueryResult<TData, TVariables>>;
useQuery(options: QueryHookOptions<TData, TVariables>): QueryResult<TData, TVariables>;
private renderPromises;
private queryHookOptions;
private watchQueryOptions;
private useOptions;
private getObsQueryOptions;
private ssrDisabledResult;
private skipStandbyResult;
private createWatchQueryOptions;
getDefaultFetchPolicy(): WatchQueryFetchPolicy;
private onCompleted;
private onError;
private observable;
private obsQueryFields;
private useObservableQuery;
private result;
private previousData;
private setResult;
private handleErrorOrCompleted;
private toApolloError;
private getCurrentResult;
private toQueryResultCache;
toQueryResult(result: ApolloQueryResult<TData>): QueryResult<TData, TVariables>;
private unsafeHandlePartialRefetch;
}
export {};
//# sourceMappingURL=useQuery.d.ts.map

View File

@@ -0,0 +1,467 @@
import { __assign, __rest } from "tslib";
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
import { equal } from "@wry/equality";
import { mergeOptions } from "../../utilities/index.js";
import { getApolloContext } from "../context/index.js";
import { ApolloError } from "../../errors/index.js";
import { NetworkStatus } from "../../core/index.js";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { canUseWeakMap, compact, isNonEmptyArray, maybeDeepFreeze, } from "../../utilities/index.js";
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* A hook for executing queries in an Apollo application.
*
* To run a query within a React component, call `useQuery` and pass it a GraphQL query document.
*
* When your component renders, `useQuery` returns an object from Apollo Client that contains `loading`, `error`, and `data` properties you can use to render your UI.
*
* > Refer to the [Queries](https://www.apollographql.com/docs/react/data/queries) section for a more in-depth overview of `useQuery`.
*
* @example
* ```jsx
* import { gql, useQuery } from '@apollo/client';
*
* const GET_GREETING = gql`
* query GetGreeting($language: String!) {
* greeting(language: $language) {
* message
* }
* }
* `;
*
* function Hello() {
* const { loading, error, data } = useQuery(GET_GREETING, {
* variables: { language: 'english' },
* });
* if (loading) return <p>Loading ...</p>;
* return <h1>Hello {data.greeting.message}!</h1>;
* }
* ```
* @since 3.0.0
* @param query - A GraphQL query document parsed into an AST by `gql`.
* @param options - Options to control how the query is executed.
* @returns Query result object
*/
export function useQuery(query, options) {
if (options === void 0) { options = Object.create(null); }
return useInternalState(useApolloClient(options.client), query).useQuery(options);
}
export function useInternalState(client, query) {
var stateRef = React.useRef();
if (!stateRef.current ||
client !== stateRef.current.client ||
query !== stateRef.current.query) {
stateRef.current = new InternalState(client, query, stateRef.current);
}
var state = stateRef.current;
// By default, InternalState.prototype.forceUpdate is an empty function, but
// we replace it here (before anyone has had a chance to see this state yet)
// with a function that unconditionally forces an update, using the latest
// setTick function. Updating this state by calling state.forceUpdate is the
// only way we trigger React component updates (no other useState calls within
// the InternalState class).
state.forceUpdateState = React.useReducer(function (tick) { return tick + 1; }, 0)[1];
return state;
}
var InternalState = /** @class */ (function () {
function InternalState(client, query, previous) {
var _this = this;
this.client = client;
this.query = query;
/**
* Will be overwritten by the `useSyncExternalStore` "force update" method
* whenever it is available and reset to `forceUpdateState` when it isn't.
*/
this.forceUpdate = function () { return _this.forceUpdateState(); };
this.ssrDisabledResult = maybeDeepFreeze({
loading: true,
data: void 0,
error: void 0,
networkStatus: NetworkStatus.loading,
});
this.skipStandbyResult = maybeDeepFreeze({
loading: false,
data: void 0,
error: void 0,
networkStatus: NetworkStatus.ready,
});
// 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.
this.toQueryResultCache = new (canUseWeakMap ? WeakMap : Map)();
verifyDocumentType(query, DocumentType.Query);
// Reuse previousData from previous InternalState (if any) to provide
// continuity of previousData even if/when the query or client changes.
var previousResult = previous && previous.result;
var previousData = previousResult && previousResult.data;
if (previousData) {
this.previousData = previousData;
}
}
/**
* Forces an update using local component state.
* As this is not batched with `useSyncExternalStore` updates,
* this is only used as a fallback if the `useSyncExternalStore` "force update"
* method is not registered at the moment.
* See https://github.com/facebook/react/issues/25191
* */
InternalState.prototype.forceUpdateState = function () {
// Replaced (in useInternalState) with a method that triggers an update.
globalThis.__DEV__ !== false && invariant.warn(51);
};
InternalState.prototype.executeQuery = function (options) {
var _this = this;
var _a;
if (options.query) {
Object.assign(this, { query: options.query });
}
this.watchQueryOptions = this.createWatchQueryOptions((this.queryHookOptions = options));
var concast = this.observable.reobserveAsConcast(this.getObsQueryOptions());
// Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,
// but save the current data as this.previousData, just like setResult
// usually does.
this.previousData = ((_a = this.result) === null || _a === void 0 ? void 0 : _a.data) || this.previousData;
this.result = void 0;
this.forceUpdate();
return new Promise(function (resolve) {
var result;
// Subscribe to the concast independently of the ObservableQuery in case
// the component gets unmounted before the promise resolves. This prevents
// the concast from terminating early and resolving with `undefined` when
// there are no more subscribers for the concast.
concast.subscribe({
next: function (value) {
result = value;
},
error: function () {
resolve(_this.toQueryResult(_this.observable.getCurrentResult()));
},
complete: function () {
resolve(_this.toQueryResult(result));
},
});
});
};
// Methods beginning with use- should be called according to the standard
// rules of React hooks: only at the top level of the calling function, and
// without any dynamic conditional logic.
InternalState.prototype.useQuery = function (options) {
var _this = this;
// The renderPromises field gets initialized here in the useQuery method, at
// the beginning of everything (for a given component rendering, at least),
// so we can safely use this.renderPromises in other/later InternalState
// methods without worrying it might be uninitialized. Even after
// initialization, this.renderPromises is usually undefined (unless SSR is
// happening), but that's fine as long as it has been initialized that way,
// rather than left uninitialized.
this.renderPromises = React.useContext(getApolloContext()).renderPromises;
this.useOptions(options);
var obsQuery = this.useObservableQuery();
var result = useSyncExternalStore(React.useCallback(function (handleStoreChange) {
if (_this.renderPromises) {
return function () { };
}
_this.forceUpdate = handleStoreChange;
var onNext = function () {
var previousResult = _this.result;
// We use `getCurrentResult()` instead of the onNext argument because
// the values differ slightly. Specifically, loading results will have
// an empty object for data instead of `undefined` for some reason.
var result = obsQuery.getCurrentResult();
// Make sure we're not attempting to re-render similar results
if (previousResult &&
previousResult.loading === result.loading &&
previousResult.networkStatus === result.networkStatus &&
equal(previousResult.data, result.data)) {
return;
}
_this.setResult(result);
};
var onError = function (error) {
subscription.unsubscribe();
subscription = obsQuery.resubscribeAfterError(onNext, onError);
if (!hasOwnProperty.call(error, "graphQLErrors")) {
// The error is not a GraphQL error
throw error;
}
var previousResult = _this.result;
if (!previousResult ||
(previousResult && previousResult.loading) ||
!equal(error, previousResult.error)) {
_this.setResult({
data: (previousResult && previousResult.data),
error: error,
loading: false,
networkStatus: NetworkStatus.error,
});
}
};
var subscription = obsQuery.subscribe(onNext, onError);
// Do the "unsubscribe" with a short delay.
// This way, an existing subscription can be reused without an additional
// request if "unsubscribe" and "resubscribe" to the same ObservableQuery
// happen in very fast succession.
return function () {
setTimeout(function () { return subscription.unsubscribe(); });
_this.forceUpdate = function () { return _this.forceUpdateState(); };
};
}, [
// We memoize the subscribe function using useCallback and the following
// dependency keys, because the subscribe function reference is all that
// useSyncExternalStore uses internally as a dependency key for the
// useEffect ultimately responsible for the subscription, so we are
// effectively passing this dependency array to that useEffect buried
// inside useSyncExternalStore, as desired.
obsQuery,
this.renderPromises,
this.client.disableNetworkFetches,
]), function () { return _this.getCurrentResult(); }, function () { return _this.getCurrentResult(); });
// TODO Remove this method when we remove support for options.partialRefetch.
this.unsafeHandlePartialRefetch(result);
return this.toQueryResult(result);
};
InternalState.prototype.useOptions = function (options) {
var _a;
var watchQueryOptions = this.createWatchQueryOptions((this.queryHookOptions = options));
// Update this.watchQueryOptions, but only when they have changed, which
// allows us to depend on the referential stability of
// this.watchQueryOptions elsewhere.
var currentWatchQueryOptions = this.watchQueryOptions;
if (!equal(watchQueryOptions, currentWatchQueryOptions)) {
this.watchQueryOptions = watchQueryOptions;
if (currentWatchQueryOptions && this.observable) {
// Though it might be tempting to postpone this reobserve call to the
// useEffect block, we need getCurrentResult to return an appropriate
// loading:true result synchronously (later within the same call to
// useQuery). Since we already have this.observable here (not true for
// the very first call to useQuery), we are not initiating any new
// subscriptions, though it does feel less than ideal that reobserve
// (potentially) kicks off a network request (for example, when the
// variables have changed), which is technically a side-effect.
this.observable.reobserve(this.getObsQueryOptions());
// Make sure getCurrentResult returns a fresh ApolloQueryResult<TData>,
// but save the current data as this.previousData, just like setResult
// usually does.
this.previousData = ((_a = this.result) === null || _a === void 0 ? void 0 : _a.data) || this.previousData;
this.result = void 0;
}
}
// Make sure state.onCompleted and state.onError always reflect the latest
// options.onCompleted and options.onError callbacks provided to useQuery,
// since those functions are often recreated every time useQuery is called.
// Like the forceUpdate method, the versions of these methods inherited from
// InternalState.prototype are empty no-ops, but we can override them on the
// base state object (without modifying the prototype).
this.onCompleted =
options.onCompleted || InternalState.prototype.onCompleted;
this.onError = options.onError || InternalState.prototype.onError;
if ((this.renderPromises || this.client.disableNetworkFetches) &&
this.queryHookOptions.ssr === false &&
!this.queryHookOptions.skip) {
// If SSR has been explicitly disabled, and this function has been called
// on the server side, return the default loading state.
this.result = this.ssrDisabledResult;
}
else if (this.queryHookOptions.skip ||
this.watchQueryOptions.fetchPolicy === "standby") {
// When skipping a query (ie. we're not querying for data but still want to
// render children), make sure the `data` is cleared out and `loading` is
// set to `false` (since we aren't loading anything).
//
// NOTE: We no longer think this is the correct behavior. Skipping should
// not automatically set `data` to `undefined`, but instead leave the
// previous data in place. In other words, skipping should not mandate that
// 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.
this.result = this.skipStandbyResult;
}
else if (this.result === this.ssrDisabledResult ||
this.result === this.skipStandbyResult) {
this.result = void 0;
}
};
InternalState.prototype.getObsQueryOptions = function () {
var toMerge = [];
var globalDefaults = this.client.defaultOptions.watchQuery;
if (globalDefaults)
toMerge.push(globalDefaults);
if (this.queryHookOptions.defaultOptions) {
toMerge.push(this.queryHookOptions.defaultOptions);
}
// We use compact rather than mergeOptions for this part of the merge,
// because we want watchQueryOptions.variables (if defined) to replace
// this.observable.options.variables whole. This replacement allows
// removing variables by removing them from the variables input to
// useQuery. If the variables were always merged together (rather than
// replaced), there would be no way to remove existing variables.
// However, the variables from options.defaultOptions and globalDefaults
// (if provided) should be merged, to ensure individual defaulted
// variables always have values, if not otherwise defined in
// observable.options or watchQueryOptions.
toMerge.push(compact(this.observable && this.observable.options, this.watchQueryOptions));
return toMerge.reduce(mergeOptions);
};
// A function to massage options before passing them to ObservableQuery.
InternalState.prototype.createWatchQueryOptions = function (_a) {
var _b;
if (_a === void 0) { _a = {}; }
var skip = _a.skip, ssr = _a.ssr, onCompleted = _a.onCompleted, onError = _a.onError, defaultOptions = _a.defaultOptions,
// The above options are useQuery-specific, so this ...otherOptions spread
// makes otherOptions almost a WatchQueryOptions object, except for the
// query property that we add below.
otherOptions = __rest(_a, ["skip", "ssr", "onCompleted", "onError", "defaultOptions"]);
// This Object.assign is safe because otherOptions is a fresh ...rest object
// that did not exist until just now, so modifications are still allowed.
var watchQueryOptions = Object.assign(otherOptions, { query: this.query });
if (this.renderPromises &&
(watchQueryOptions.fetchPolicy === "network-only" ||
watchQueryOptions.fetchPolicy === "cache-and-network")) {
// this behavior was added to react-apollo without explanation in this PR
// https://github.com/apollographql/react-apollo/pull/1579
watchQueryOptions.fetchPolicy = "cache-first";
}
if (!watchQueryOptions.variables) {
watchQueryOptions.variables = {};
}
if (skip) {
var _c = watchQueryOptions.fetchPolicy, fetchPolicy = _c === void 0 ? this.getDefaultFetchPolicy() : _c, _d = watchQueryOptions.initialFetchPolicy, initialFetchPolicy = _d === void 0 ? fetchPolicy : _d;
// When skipping, we set watchQueryOptions.fetchPolicy initially to
// "standby", but we also need/want to preserve the initial non-standby
// fetchPolicy that would have been used if not skipping.
Object.assign(watchQueryOptions, {
initialFetchPolicy: initialFetchPolicy,
fetchPolicy: "standby",
});
}
else if (!watchQueryOptions.fetchPolicy) {
watchQueryOptions.fetchPolicy =
((_b = this.observable) === null || _b === void 0 ? void 0 : _b.options.initialFetchPolicy) ||
this.getDefaultFetchPolicy();
}
return watchQueryOptions;
};
InternalState.prototype.getDefaultFetchPolicy = function () {
var _a, _b;
return (((_a = this.queryHookOptions.defaultOptions) === null || _a === void 0 ? void 0 : _a.fetchPolicy) ||
((_b = this.client.defaultOptions.watchQuery) === null || _b === void 0 ? void 0 : _b.fetchPolicy) ||
"cache-first");
};
// Defining these methods as no-ops on the prototype allows us to call
// state.onCompleted and/or state.onError without worrying about whether a
// callback was provided.
InternalState.prototype.onCompleted = function (data) { };
InternalState.prototype.onError = function (error) { };
InternalState.prototype.useObservableQuery = function () {
// 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.
var obsQuery = (this.observable =
(this.renderPromises &&
this.renderPromises.getSSRObservable(this.watchQueryOptions)) ||
this.observable || // Reuse this.observable if possible (and not SSR)
this.client.watchQuery(this.getObsQueryOptions()));
this.obsQueryFields = React.useMemo(function () { return ({
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]);
var ssrAllowed = !(this.queryHookOptions.ssr === false || this.queryHookOptions.skip);
if (this.renderPromises && ssrAllowed) {
this.renderPromises.registerSSRObservable(obsQuery);
if (obsQuery.getCurrentResult().loading) {
// TODO: This is a legacy API which could probably be cleaned up
this.renderPromises.addObservableQueryPromise(obsQuery);
}
}
return obsQuery;
};
InternalState.prototype.setResult = function (nextResult) {
var previousResult = this.result;
if (previousResult && previousResult.data) {
this.previousData = previousResult.data;
}
this.result = nextResult;
// Calling state.setResult always triggers an update, though some call sites
// perform additional equality checks before committing to an update.
this.forceUpdate();
this.handleErrorOrCompleted(nextResult, previousResult);
};
InternalState.prototype.handleErrorOrCompleted = function (result, previousResult) {
var _this = this;
if (!result.loading) {
var error_1 = this.toApolloError(result);
// wait a tick in case we are in the middle of rendering a component
Promise.resolve()
.then(function () {
if (error_1) {
_this.onError(error_1);
}
else if (result.data &&
(previousResult === null || previousResult === void 0 ? void 0 : previousResult.networkStatus) !== result.networkStatus &&
result.networkStatus === NetworkStatus.ready) {
_this.onCompleted(result.data);
}
})
.catch(function (error) {
globalThis.__DEV__ !== false && invariant.warn(error);
});
}
};
InternalState.prototype.toApolloError = function (result) {
return isNonEmptyArray(result.errors) ?
new ApolloError({ graphQLErrors: result.errors })
: result.error;
};
InternalState.prototype.getCurrentResult = function () {
// 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.
if (!this.result) {
this.handleErrorOrCompleted((this.result = this.observable.getCurrentResult()));
}
return this.result;
};
InternalState.prototype.toQueryResult = function (result) {
var queryResult = this.toQueryResultCache.get(result);
if (queryResult)
return queryResult;
var data = result.data, partial = result.partial, resultWithoutPartial = __rest(result, ["data", "partial"]);
this.toQueryResultCache.set(result, (queryResult = __assign(__assign(__assign({ data: data }, resultWithoutPartial), this.obsQueryFields), { client: this.client, observable: this.observable, variables: this.observable.variables, called: !this.queryHookOptions.skip, previousData: this.previousData })));
if (!queryResult.error && isNonEmptyArray(result.errors)) {
// Until a set naming convention for networkError and graphQLErrors is
// decided upon, we map errors (graphQLErrors) to the error options.
// TODO: Is it possible for both result.error and result.errors to be
// defined here?
queryResult.error = new ApolloError({ graphQLErrors: result.errors });
}
return queryResult;
};
InternalState.prototype.unsafeHandlePartialRefetch = function (result) {
// WARNING: SIDE-EFFECTS IN THE RENDER FUNCTION
//
// TODO: This code should be removed when the partialRefetch option is
// removed. I was unable to get this hook to behave reasonably in certain
// edge cases when this block was put in an effect.
if (result.partial &&
this.queryHookOptions.partialRefetch &&
!result.loading &&
(!result.data || Object.keys(result.data).length === 0) &&
this.observable.options.fetchPolicy !== "cache-only") {
Object.assign(result, {
loading: true,
networkStatus: NetworkStatus.refetch,
});
this.observable.refetch();
}
};
return InternalState;
}());
//# sourceMappingURL=useQuery.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
import type { QueryReference } from "../internal/index.js";
import type { OperationVariables } from "../../core/types.js";
import type { RefetchFunction, FetchMoreFunction } from "./useSuspenseQuery.js";
export interface UseQueryRefHandlersResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> {
/**
* Update the variables of this observable query, and fetch the new results. This method should be preferred over `setVariables` in most use cases.
*
* @param variables - The new set of variables. If there are missing variables, the previous values of those variables will be used.
*/
refetch: RefetchFunction<TData, TVariables>;
/**
* A function that helps you fetch the next set of results for a [paginated list field](https://www.apollographql.com/docs/react/pagination/core-api/).
*/
fetchMore: FetchMoreFunction<TData, TVariables>;
}
/**
* A React hook that returns a `refetch` and `fetchMore` function for a given
* `queryRef`.
*
* This is useful to get access to handlers for a `queryRef` that was created by
* `createQueryPreloader` or when the handlers for a `queryRef` produced in
* a different component are inaccessible.
*
* @example
* ```tsx
* const MyComponent({ queryRef }) {
* const { refetch, fetchMore } = useQueryRefHandlers(queryRef);
*
* // ...
* }
* ```
* @since 3.9.0
* @param queryRef - A `QueryReference` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.
*/
export declare function useQueryRefHandlers<TData = unknown, TVariables extends OperationVariables = OperationVariables>(queryRef: QueryReference<TData, TVariables>): UseQueryRefHandlersResult<TData, TVariables>;
//# sourceMappingURL=useQueryRefHandlers.d.ts.map

View File

@@ -0,0 +1,48 @@
import * as React from "rehackt";
import { getWrappedPromise, unwrapQueryRef, updateWrappedQueryRef, wrapQueryRef, } from "../internal/index.js";
/**
* A React hook that returns a `refetch` and `fetchMore` function for a given
* `queryRef`.
*
* This is useful to get access to handlers for a `queryRef` that was created by
* `createQueryPreloader` or when the handlers for a `queryRef` produced in
* a different component are inaccessible.
*
* @example
* ```tsx
* const MyComponent({ queryRef }) {
* const { refetch, fetchMore } = useQueryRefHandlers(queryRef);
*
* // ...
* }
* ```
* @since 3.9.0
* @param queryRef - A `QueryReference` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.
*/
export function useQueryRefHandlers(queryRef) {
var _a = React.useState(queryRef), previousQueryRef = _a[0], setPreviousQueryRef = _a[1];
var _b = React.useState(queryRef), wrappedQueryRef = _b[0], setWrappedQueryRef = _b[1];
var internalQueryRef = unwrapQueryRef(queryRef);
// To ensure we can support React transitions, this hook needs to manage the
// queryRef state and apply React's state value immediately to the existing
// queryRef since this hook doesn't return the queryRef directly
if (previousQueryRef !== queryRef) {
setPreviousQueryRef(queryRef);
setWrappedQueryRef(queryRef);
}
else {
updateWrappedQueryRef(queryRef, getWrappedPromise(wrappedQueryRef));
}
var refetch = React.useCallback(function (variables) {
var promise = internalQueryRef.refetch(variables);
setWrappedQueryRef(wrapQueryRef(internalQueryRef));
return promise;
}, [internalQueryRef]);
var fetchMore = React.useCallback(function (options) {
var promise = internalQueryRef.fetchMore(options);
setWrappedQueryRef(wrapQueryRef(internalQueryRef));
return promise;
}, [internalQueryRef]);
return { refetch: refetch, fetchMore: fetchMore };
}
//# sourceMappingURL=useQueryRefHandlers.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useQueryRefHandlers.js","sourceRoot":"","sources":["../../../src/react/hooks/useQueryRefHandlers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,qBAAqB,EACrB,YAAY,GACb,MAAM,sBAAsB,CAAC;AAgB9B;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,UAAU,mBAAmB,CAIjC,QAA2C;IAErC,IAAA,KAA0C,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAjE,gBAAgB,QAAA,EAAE,mBAAmB,QAA4B,CAAC;IACnE,IAAA,KAAwC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAA/D,eAAe,QAAA,EAAE,kBAAkB,QAA4B,CAAC;IACvE,IAAM,gBAAgB,GAAG,cAAc,CAAC,QAAQ,CAAC,CAAC;IAElD,4EAA4E;IAC5E,2EAA2E;IAC3E,gEAAgE;IAChE,IAAI,gBAAgB,KAAK,QAAQ,EAAE,CAAC;QAClC,mBAAmB,CAAC,QAAQ,CAAC,CAAC;QAC9B,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IAC/B,CAAC;SAAM,CAAC;QACN,qBAAqB,CAAC,QAAQ,EAAE,iBAAiB,CAAC,eAAe,CAAC,CAAC,CAAC;IACtE,CAAC;IAED,IAAM,OAAO,GAAuC,KAAK,CAAC,WAAW,CACnE,UAAC,SAAS;QACR,IAAM,OAAO,GAAG,gBAAgB,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAEpD,kBAAkB,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC;QAEnD,OAAO,OAAO,CAAC;IACjB,CAAC,EACD,CAAC,gBAAgB,CAAC,CACnB,CAAC;IAEF,IAAM,SAAS,GAAyC,KAAK,CAAC,WAAW,CACvE,UAAC,OAAO;QACN,IAAM,OAAO,GAAG,gBAAgB,CAAC,SAAS,CACxC,OAA0C,CAC3C,CAAC;QAEF,kBAAkB,CAAC,YAAY,CAAC,gBAAgB,CAAC,CAAC,CAAC;QAEnD,OAAO,OAAO,CAAC;IACjB,CAAC,EACD,CAAC,gBAAgB,CAAC,CACnB,CAAC;IAEF,OAAO,EAAE,OAAO,SAAA,EAAE,SAAS,WAAA,EAAE,CAAC;AAChC,CAAC","sourcesContent":["import * as React from \"rehackt\";\nimport {\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n wrapQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryReference } from \"../internal/index.js\";\nimport type { OperationVariables } from \"../../core/types.js\";\nimport type { RefetchFunction, FetchMoreFunction } from \"./useSuspenseQuery.js\";\nimport type { FetchMoreQueryOptions } from \"../../core/watchQueryOptions.js\";\n\nexport interface UseQueryRefHandlersResult<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n> {\n /** {@inheritDoc @apollo/client!ObservableQuery#refetch:member(1)} */\n refetch: RefetchFunction<TData, TVariables>;\n /** {@inheritDoc @apollo/client!ObservableQuery#fetchMore:member(1)} */\n fetchMore: FetchMoreFunction<TData, TVariables>;\n}\n\n/**\n * A React hook that returns a `refetch` and `fetchMore` function for a given\n * `queryRef`.\n *\n * This is useful to get access to handlers for a `queryRef` that was created by\n * `createQueryPreloader` or when the handlers for a `queryRef` produced in\n * a different component are inaccessible.\n *\n * @example\n * ```tsx\n * const MyComponent({ queryRef }) {\n * const { refetch, fetchMore } = useQueryRefHandlers(queryRef);\n *\n * // ...\n * }\n * ```\n * @since 3.9.0\n * @param queryRef - A `QueryReference` returned from `useBackgroundQuery`, `useLoadableQuery`, or `createQueryPreloader`.\n */\nexport function useQueryRefHandlers<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n>(\n queryRef: QueryReference<TData, TVariables>\n): UseQueryRefHandlersResult<TData, TVariables> {\n const [previousQueryRef, setPreviousQueryRef] = React.useState(queryRef);\n const [wrappedQueryRef, setWrappedQueryRef] = React.useState(queryRef);\n const internalQueryRef = unwrapQueryRef(queryRef);\n\n // To ensure we can support React transitions, this hook needs to manage the\n // queryRef state and apply React's state value immediately to the existing\n // queryRef since this hook doesn't return the queryRef directly\n if (previousQueryRef !== queryRef) {\n setPreviousQueryRef(queryRef);\n setWrappedQueryRef(queryRef);\n } else {\n updateWrappedQueryRef(queryRef, getWrappedPromise(wrappedQueryRef));\n }\n\n const refetch: RefetchFunction<TData, TVariables> = React.useCallback(\n (variables) => {\n const promise = internalQueryRef.refetch(variables);\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n const fetchMore: FetchMoreFunction<TData, TVariables> = React.useCallback(\n (options) => {\n const promise = internalQueryRef.fetchMore(\n options as FetchMoreQueryOptions<any, any>\n );\n\n setWrappedQueryRef(wrapQueryRef(internalQueryRef));\n\n return promise;\n },\n [internalQueryRef]\n );\n\n return { refetch, fetchMore };\n}\n"]}

View File

@@ -0,0 +1,20 @@
import type { ReactiveVar } from "../../core/index.js";
/**
* Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.
*
* @example
* ```jsx
* import { makeVar, useReactiveVar } from "@apollo/client";
* export const cartItemsVar = makeVar([]);
*
* export function Cart() {
* const cartItems = useReactiveVar(cartItemsVar);
* // ...
* }
* ```
* @since 3.2.0
* @param rv - A reactive variable.
* @returns The current value of the reactive variable.
*/
export declare function useReactiveVar<T>(rv: ReactiveVar<T>): T;
//# sourceMappingURL=useReactiveVar.d.ts.map

View File

@@ -0,0 +1,33 @@
import * as React from "rehackt";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
/**
* Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.
*
* @example
* ```jsx
* import { makeVar, useReactiveVar } from "@apollo/client";
* export const cartItemsVar = makeVar([]);
*
* export function Cart() {
* const cartItems = useReactiveVar(cartItemsVar);
* // ...
* }
* ```
* @since 3.2.0
* @param rv - A reactive variable.
* @returns The current value of the reactive variable.
*/
export function useReactiveVar(rv) {
return useSyncExternalStore(React.useCallback(function (update) {
// By reusing the same onNext function in the nested call to
// rv.onNextChange(onNext), we can keep using the initial clean-up function
// returned by rv.onNextChange(function onNext(v){...}), without having to
// register the new clean-up function (returned by the nested
// rv.onNextChange(onNext)) with yet another callback.
return rv.onNextChange(function onNext() {
update();
rv.onNextChange(onNext);
});
}, [rv]), rv, rv);
}
//# sourceMappingURL=useReactiveVar.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useReactiveVar.js","sourceRoot":"","sources":["../../../src/react/hooks/useReactiveVar.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AAEjC,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEjE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,UAAU,cAAc,CAAI,EAAkB;IAClD,OAAO,oBAAoB,CACzB,KAAK,CAAC,WAAW,CACf,UAAC,MAAM;QACL,4DAA4D;QAC5D,2EAA2E;QAC3E,0EAA0E;QAC1E,6DAA6D;QAC7D,sDAAsD;QACtD,OAAO,EAAE,CAAC,YAAY,CAAC,SAAS,MAAM;YACpC,MAAM,EAAE,CAAC;YACT,EAAE,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACL,CAAC,EACD,CAAC,EAAE,CAAC,CACL,EACD,EAAE,EACF,EAAE,CACH,CAAC;AACJ,CAAC","sourcesContent":["import * as React from \"rehackt\";\nimport type { ReactiveVar } from \"../../core/index.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\n\n/**\n * Reads the value of a [reactive variable](https://www.apollographql.com/docs/react/local-state/reactive-variables/) and re-renders the containing component whenever that variable's value changes. This enables a reactive variable to trigger changes _without_ relying on the `useQuery` hook.\n *\n * @example\n * ```jsx\n * import { makeVar, useReactiveVar } from \"@apollo/client\";\n * export const cartItemsVar = makeVar([]);\n *\n * export function Cart() {\n * const cartItems = useReactiveVar(cartItemsVar);\n * // ...\n * }\n * ```\n * @since 3.2.0\n * @param rv - A reactive variable.\n * @returns The current value of the reactive variable.\n */\nexport function useReactiveVar<T>(rv: ReactiveVar<T>): T {\n return useSyncExternalStore(\n React.useCallback(\n (update) => {\n // By reusing the same onNext function in the nested call to\n // rv.onNextChange(onNext), we can keep using the initial clean-up function\n // returned by rv.onNextChange(function onNext(v){...}), without having to\n // register the new clean-up function (returned by the nested\n // rv.onNextChange(onNext)) with yet another callback.\n return rv.onNextChange(function onNext() {\n update();\n rv.onNextChange(onNext);\n });\n },\n [rv]\n ),\n rv,\n rv\n );\n}\n"]}

View File

@@ -0,0 +1,29 @@
import type { QueryReference } from "../internal/index.js";
import type { ApolloError } from "../../errors/index.js";
import type { NetworkStatus } from "../../core/index.js";
export interface UseReadQueryResult<TData = unknown> {
/**
* An object containing the result of your GraphQL query after it completes.
*
* This value might be `undefined` if a query results in one or more errors
* (depending on the query's `errorPolicy`).
*/
data: TData;
/**
* If the query produces one or more errors, this object contains either an
* array of `graphQLErrors` or a single `networkError`. Otherwise, this value
* is `undefined`.
*
* This property can be ignored when using the default `errorPolicy` or an
* `errorPolicy` of `none`. The hook will throw the error instead of setting
* this property.
*/
error: ApolloError | undefined;
/**
* A number indicating the current network state of the query's associated
* request. {@link https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4 | See possible values}.
*/
networkStatus: NetworkStatus;
}
export declare function useReadQuery<TData>(queryRef: QueryReference<TData>): UseReadQueryResult<TData>;
//# sourceMappingURL=useReadQuery.d.ts.map

View File

@@ -0,0 +1,29 @@
import * as React from "rehackt";
import { getWrappedPromise, unwrapQueryRef, updateWrappedQueryRef, } from "../internal/index.js";
import { __use } from "./internal/index.js";
import { toApolloError } from "./useSuspenseQuery.js";
import { useSyncExternalStore } from "./useSyncExternalStore.js";
export function useReadQuery(queryRef) {
var internalQueryRef = React.useMemo(function () { return unwrapQueryRef(queryRef); }, [queryRef]);
var getPromise = React.useCallback(function () { return getWrappedPromise(queryRef); }, [queryRef]);
if (internalQueryRef.disposed) {
internalQueryRef.reinitialize();
updateWrappedQueryRef(queryRef, internalQueryRef.promise);
}
React.useEffect(function () { return internalQueryRef.retain(); }, [internalQueryRef]);
var promise = useSyncExternalStore(React.useCallback(function (forceUpdate) {
return internalQueryRef.listen(function (promise) {
updateWrappedQueryRef(queryRef, promise);
forceUpdate();
});
}, [internalQueryRef]), getPromise, getPromise);
var result = __use(promise);
return React.useMemo(function () {
return {
data: result.data,
networkStatus: result.networkStatus,
error: toApolloError(result),
};
}, [result]);
}
//# sourceMappingURL=useReadQuery.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"useReadQuery.js","sourceRoot":"","sources":["../../../src/react/hooks/useReadQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,SAAS,CAAC;AACjC,OAAO,EACL,iBAAiB,EACjB,cAAc,EACd,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EAAE,KAAK,EAAE,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AA6BjE,MAAM,UAAU,YAAY,CAC1B,QAA+B;IAE/B,IAAM,gBAAgB,GAAG,KAAK,CAAC,OAAO,CACpC,cAAM,OAAA,cAAc,CAAC,QAAQ,CAAC,EAAxB,CAAwB,EAC9B,CAAC,QAAQ,CAAC,CACX,CAAC;IAEF,IAAM,UAAU,GAAG,KAAK,CAAC,WAAW,CAClC,cAAM,OAAA,iBAAiB,CAAC,QAAQ,CAAC,EAA3B,CAA2B,EACjC,CAAC,QAAQ,CAAC,CACX,CAAC;IAEF,IAAI,gBAAgB,CAAC,QAAQ,EAAE,CAAC;QAC9B,gBAAgB,CAAC,YAAY,EAAE,CAAC;QAChC,qBAAqB,CAAC,QAAQ,EAAE,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAC5D,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,cAAM,OAAA,gBAAgB,CAAC,MAAM,EAAE,EAAzB,CAAyB,EAAE,CAAC,gBAAgB,CAAC,CAAC,CAAC;IAErE,IAAM,OAAO,GAAG,oBAAoB,CAClC,KAAK,CAAC,WAAW,CACf,UAAC,WAAW;QACV,OAAO,gBAAgB,CAAC,MAAM,CAAC,UAAC,OAAO;YACrC,qBAAqB,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;YACzC,WAAW,EAAE,CAAC;QAChB,CAAC,CAAC,CAAC;IACL,CAAC,EACD,CAAC,gBAAgB,CAAC,CACnB,EACD,UAAU,EACV,UAAU,CACX,CAAC;IAEF,IAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC;IAE9B,OAAO,KAAK,CAAC,OAAO,CAAC;QACnB,OAAO;YACL,IAAI,EAAE,MAAM,CAAC,IAAI;YACjB,aAAa,EAAE,MAAM,CAAC,aAAa;YACnC,KAAK,EAAE,aAAa,CAAC,MAAM,CAAC;SAC7B,CAAC;IACJ,CAAC,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;AACf,CAAC","sourcesContent":["import * as React from \"rehackt\";\nimport {\n getWrappedPromise,\n unwrapQueryRef,\n updateWrappedQueryRef,\n} from \"../internal/index.js\";\nimport type { QueryReference } from \"../internal/index.js\";\nimport { __use } from \"./internal/index.js\";\nimport { toApolloError } from \"./useSuspenseQuery.js\";\nimport { useSyncExternalStore } from \"./useSyncExternalStore.js\";\nimport type { ApolloError } from \"../../errors/index.js\";\nimport type { NetworkStatus } from \"../../core/index.js\";\n\nexport interface UseReadQueryResult<TData = unknown> {\n /**\n * An object containing the result of your GraphQL query after it completes.\n *\n * This value might be `undefined` if a query results in one or more errors\n * (depending on the query's `errorPolicy`).\n */\n data: TData;\n /**\n * If the query produces one or more errors, this object contains either an\n * array of `graphQLErrors` or a single `networkError`. Otherwise, this value\n * is `undefined`.\n *\n * This property can be ignored when using the default `errorPolicy` or an\n * `errorPolicy` of `none`. The hook will throw the error instead of setting\n * this property.\n */\n error: ApolloError | undefined;\n /**\n * A number indicating the current network state of the query's associated\n * request. {@link https://github.com/apollographql/apollo-client/blob/d96f4578f89b933c281bb775a39503f6cdb59ee8/src/core/networkStatus.ts#L4 | See possible values}.\n */\n networkStatus: NetworkStatus;\n}\n\nexport function useReadQuery<TData>(\n queryRef: QueryReference<TData>\n): UseReadQueryResult<TData> {\n const internalQueryRef = React.useMemo(\n () => unwrapQueryRef(queryRef),\n [queryRef]\n );\n\n const getPromise = React.useCallback(\n () => getWrappedPromise(queryRef),\n [queryRef]\n );\n\n if (internalQueryRef.disposed) {\n internalQueryRef.reinitialize();\n updateWrappedQueryRef(queryRef, internalQueryRef.promise);\n }\n\n React.useEffect(() => internalQueryRef.retain(), [internalQueryRef]);\n\n const promise = useSyncExternalStore(\n React.useCallback(\n (forceUpdate) => {\n return internalQueryRef.listen((promise) => {\n updateWrappedQueryRef(queryRef, promise);\n forceUpdate();\n });\n },\n [internalQueryRef]\n ),\n getPromise,\n getPromise\n );\n\n const result = __use(promise);\n\n return React.useMemo(() => {\n return {\n data: result.data,\n networkStatus: result.networkStatus,\n error: toApolloError(result),\n };\n }, [result]);\n}\n"]}

View File

@@ -0,0 +1,91 @@
import type { DocumentNode } from "graphql";
import type { TypedDocumentNode } from "@graphql-typed-document-node/core";
import type { NoInfer, SubscriptionHookOptions, SubscriptionResult } from "../types/types.js";
import type { OperationVariables } from "../../core/index.js";
/**
* > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.
*
* @example
* ```jsx
* const COMMENTS_SUBSCRIPTION = gql`
* subscription OnCommentAdded($repoFullName: String!) {
* commentAdded(repoFullName: $repoFullName) {
* id
* content
* }
* }
* `;
*
* function DontReadTheComments({ repoFullName }) {
* const {
* data: { commentAdded },
* loading,
* } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
* return <h4>New comment: {!loading && commentAdded.content}</h4>;
* }
* ```
* @remarks
* #### Subscriptions and React 18 Automatic Batching
*
* With React 18's [automatic batching](https://react.dev/blog/2022/03/29/react-v18#new-feature-automatic-batching), multiple state updates may be grouped into a single re-render for better performance.
*
* If your subscription API sends multiple messages at the same time or in very fast succession (within fractions of a millisecond), it is likely that only the last message received in that narrow time frame will result in a re-render.
*
* Consider the following component:
*
* ```jsx
* export function Subscriptions() {
* const { data, error, loading } = useSubscription(query);
* const [accumulatedData, setAccumulatedData] = useState([]);
*
* useEffect(() => {
* setAccumulatedData((prev) => [...prev, data]);
* }, [data]);
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* If your subscription back-end emits two messages with the same timestamp, only the last message received by Apollo Client will be rendered. This is because React 18 will batch these two state updates into a single re-render.
*
* Since the component above is using `useEffect` to push `data` into a piece of local state on each `Subscriptions` re-render, the first message will never be added to the `accumulatedData` array since its render was skipped.
*
* Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:
*
* ```jsx
* export function Subscriptions() {
* const [accumulatedData, setAccumulatedData] = useState([]);
* const { data, error, loading } = useSubscription(
* query,
* {
* onData({ data }) {
* setAccumulatedData((prev) => [...prev, data])
* }
* }
* );
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.
*
* Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.
*
* @since 3.0.0
* @param subscription - A GraphQL subscription document parsed into an AST by `gql`.
* @param options - Options to control how the subscription is executed.
* @returns Query result object
*/
export declare function useSubscription<TData = any, TVariables extends OperationVariables = OperationVariables>(subscription: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SubscriptionHookOptions<NoInfer<TData>, NoInfer<TVariables>>): SubscriptionResult<TData, TVariables>;
//# sourceMappingURL=useSubscription.d.ts.map

View File

@@ -0,0 +1,239 @@
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { equal } from "@wry/equality";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { useApolloClient } from "./useApolloClient.js";
/**
* > Refer to the [Subscriptions](https://www.apollographql.com/docs/react/data/subscriptions/) section for a more in-depth overview of `useSubscription`.
*
* @example
* ```jsx
* const COMMENTS_SUBSCRIPTION = gql`
* subscription OnCommentAdded($repoFullName: String!) {
* commentAdded(repoFullName: $repoFullName) {
* id
* content
* }
* }
* `;
*
* function DontReadTheComments({ repoFullName }) {
* const {
* data: { commentAdded },
* loading,
* } = useSubscription(COMMENTS_SUBSCRIPTION, { variables: { repoFullName } });
* return <h4>New comment: {!loading && commentAdded.content}</h4>;
* }
* ```
* @remarks
* #### Subscriptions and React 18 Automatic Batching
*
* With React 18's [automatic batching](https://react.dev/blog/2022/03/29/react-v18#new-feature-automatic-batching), multiple state updates may be grouped into a single re-render for better performance.
*
* If your subscription API sends multiple messages at the same time or in very fast succession (within fractions of a millisecond), it is likely that only the last message received in that narrow time frame will result in a re-render.
*
* Consider the following component:
*
* ```jsx
* export function Subscriptions() {
* const { data, error, loading } = useSubscription(query);
* const [accumulatedData, setAccumulatedData] = useState([]);
*
* useEffect(() => {
* setAccumulatedData((prev) => [...prev, data]);
* }, [data]);
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* If your subscription back-end emits two messages with the same timestamp, only the last message received by Apollo Client will be rendered. This is because React 18 will batch these two state updates into a single re-render.
*
* Since the component above is using `useEffect` to push `data` into a piece of local state on each `Subscriptions` re-render, the first message will never be added to the `accumulatedData` array since its render was skipped.
*
* Instead of using `useEffect` here, we can re-write this component to use the `onData` callback function accepted in `useSubscription`'s `options` object:
*
* ```jsx
* export function Subscriptions() {
* const [accumulatedData, setAccumulatedData] = useState([]);
* const { data, error, loading } = useSubscription(
* query,
* {
* onData({ data }) {
* setAccumulatedData((prev) => [...prev, data])
* }
* }
* );
*
* return (
* <>
* {loading && <p>Loading...</p>}
* {JSON.stringify(accumulatedData, undefined, 2)}
* </>
* );
* }
* ```
*
* > ⚠️ **Note:** The `useSubscription` option `onData` is available in Apollo Client >= 3.7. In previous versions, the equivalent option is named `onSubscriptionData`.
*
* Now, the first message will be added to the `accumulatedData` array since `onData` is called _before_ the component re-renders. React 18 automatic batching is still in effect and results in a single re-render, but with `onData` we can guarantee each message received after the component mounts is added to `accumulatedData`.
*
* @since 3.0.0
* @param subscription - A GraphQL subscription document parsed into an AST by `gql`.
* @param options - Options to control how the subscription is executed.
* @returns Query result object
*/
export function useSubscription(subscription, options) {
var hasIssuedDeprecationWarningRef = React.useRef(false);
var client = useApolloClient(options === null || options === void 0 ? void 0 : options.client);
verifyDocumentType(subscription, DocumentType.Subscription);
var _a = React.useState({
loading: !(options === null || options === void 0 ? void 0 : options.skip),
error: void 0,
data: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
}), result = _a[0], setResult = _a[1];
if (!hasIssuedDeprecationWarningRef.current) {
hasIssuedDeprecationWarningRef.current = true;
if (options === null || options === void 0 ? void 0 : options.onSubscriptionData) {
globalThis.__DEV__ !== false && invariant.warn(options.onData ? 52 : 53);
}
if (options === null || options === void 0 ? void 0 : options.onSubscriptionComplete) {
globalThis.__DEV__ !== false && invariant.warn(options.onComplete ? 54 : 55);
}
}
var _b = React.useState(function () {
if (options === null || options === void 0 ? void 0 : options.skip) {
return null;
}
return client.subscribe({
query: subscription,
variables: options === null || options === void 0 ? void 0 : options.variables,
fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,
context: options === null || options === void 0 ? void 0 : options.context,
});
}), observable = _b[0], setObservable = _b[1];
var canResetObservableRef = React.useRef(false);
React.useEffect(function () {
return function () {
canResetObservableRef.current = true;
};
}, []);
var ref = React.useRef({ client: client, subscription: subscription, options: options });
React.useEffect(function () {
var _a, _b, _c, _d;
var shouldResubscribe = options === null || options === void 0 ? void 0 : options.shouldResubscribe;
if (typeof shouldResubscribe === "function") {
shouldResubscribe = !!shouldResubscribe(options);
}
if (options === null || options === void 0 ? void 0 : options.skip) {
if (!(options === null || options === void 0 ? void 0 : options.skip) !== !((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.skip) ||
canResetObservableRef.current) {
setResult({
loading: false,
data: void 0,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
setObservable(null);
canResetObservableRef.current = false;
}
}
else if ((shouldResubscribe !== false &&
(client !== ref.current.client ||
subscription !== ref.current.subscription ||
(options === null || options === void 0 ? void 0 : options.fetchPolicy) !== ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.fetchPolicy) ||
!(options === null || options === void 0 ? void 0 : options.skip) !== !((_c = ref.current.options) === null || _c === void 0 ? void 0 : _c.skip) ||
!equal(options === null || options === void 0 ? void 0 : options.variables, (_d = ref.current.options) === null || _d === void 0 ? void 0 : _d.variables))) ||
canResetObservableRef.current) {
setResult({
loading: true,
data: void 0,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
setObservable(client.subscribe({
query: subscription,
variables: options === null || options === void 0 ? void 0 : options.variables,
fetchPolicy: options === null || options === void 0 ? void 0 : options.fetchPolicy,
context: options === null || options === void 0 ? void 0 : options.context,
}));
canResetObservableRef.current = false;
}
Object.assign(ref.current, { client: client, subscription: subscription, options: options });
}, [client, subscription, options, canResetObservableRef.current]);
React.useEffect(function () {
if (!observable) {
return;
}
var subscriptionStopped = false;
var subscription = observable.subscribe({
next: function (fetchResult) {
var _a, _b;
if (subscriptionStopped) {
return;
}
var result = {
loading: false,
// TODO: fetchResult.data can be null but SubscriptionResult.data
// expects TData | undefined only
data: fetchResult.data,
error: void 0,
variables: options === null || options === void 0 ? void 0 : options.variables,
};
setResult(result);
if ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onData) {
ref.current.options.onData({
client: client,
data: result,
});
}
else if ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onSubscriptionData) {
ref.current.options.onSubscriptionData({
client: client,
subscriptionData: result,
});
}
},
error: function (error) {
var _a, _b;
if (!subscriptionStopped) {
setResult({
loading: false,
data: void 0,
error: error,
variables: options === null || options === void 0 ? void 0 : options.variables,
});
(_b = (_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error);
}
},
complete: function () {
var _a, _b;
if (!subscriptionStopped) {
if ((_a = ref.current.options) === null || _a === void 0 ? void 0 : _a.onComplete) {
ref.current.options.onComplete();
}
else if ((_b = ref.current.options) === null || _b === void 0 ? void 0 : _b.onSubscriptionComplete) {
ref.current.options.onSubscriptionComplete();
}
}
},
});
return function () {
// immediately stop receiving subscription values, but do not unsubscribe
// until after a short delay in case another useSubscription hook is
// reusing the same underlying observable and is about to subscribe
subscriptionStopped = true;
setTimeout(function () {
subscription.unsubscribe();
});
};
}, [observable]);
return result;
}
//# sourceMappingURL=useSubscription.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,54 @@
import type { ApolloClient, ApolloQueryResult, DocumentNode, OperationVariables, TypedDocumentNode, FetchMoreQueryOptions, WatchQueryOptions } from "../../core/index.js";
import { ApolloError, NetworkStatus } from "../../core/index.js";
import type { DeepPartial } from "../../utilities/index.js";
import type { SuspenseQueryHookOptions, ObservableQueryFields, NoInfer } from "../types/types.js";
import type { SkipToken } from "./constants.js";
export interface UseSuspenseQueryResult<TData = unknown, TVariables extends OperationVariables = OperationVariables> {
client: ApolloClient<any>;
data: TData;
error: ApolloError | undefined;
fetchMore: FetchMoreFunction<TData, TVariables>;
networkStatus: NetworkStatus;
refetch: RefetchFunction<TData, TVariables>;
subscribeToMore: SubscribeToMoreFunction<TData, TVariables>;
}
export type FetchMoreFunction<TData, TVariables extends OperationVariables> = (fetchMoreOptions: FetchMoreQueryOptions<TVariables, TData> & {
updateQuery?: (previousQueryResult: TData, options: {
fetchMoreResult: TData;
variables: TVariables;
}) => TData;
}) => Promise<ApolloQueryResult<TData>>;
export type RefetchFunction<TData, TVariables extends OperationVariables> = ObservableQueryFields<TData, TVariables>["refetch"];
export type SubscribeToMoreFunction<TData, TVariables extends OperationVariables> = ObservableQueryFields<TData, TVariables>["subscribeToMore"];
export declare function useSuspenseQuery<TData, TVariables extends OperationVariables, TOptions extends Omit<SuspenseQueryHookOptions<TData>, "variables">>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & TOptions): UseSuspenseQueryResult<TOptions["errorPolicy"] extends "ignore" | "all" ? TOptions["returnPartialData"] extends true ? DeepPartial<TData> | undefined : TData | undefined : TOptions["returnPartialData"] extends true ? TOptions["skip"] extends boolean ? DeepPartial<TData> | undefined : DeepPartial<TData> : TOptions["skip"] extends boolean ? TData | undefined : TData, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
errorPolicy: "ignore" | "all";
}): UseSuspenseQueryResult<DeepPartial<TData> | undefined, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
errorPolicy: "ignore" | "all";
}): UseSuspenseQueryResult<TData | undefined, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
skip: boolean;
returnPartialData: true;
}): UseSuspenseQueryResult<DeepPartial<TData> | undefined, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
}): UseSuspenseQueryResult<DeepPartial<TData>, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
skip: boolean;
}): UseSuspenseQueryResult<TData | undefined, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>): UseSuspenseQueryResult<TData, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options: SkipToken | (SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>> & {
returnPartialData: true;
})): UseSuspenseQueryResult<DeepPartial<TData> | undefined, TVariables>;
export declare function useSuspenseQuery<TData = unknown, TVariables extends OperationVariables = OperationVariables>(query: DocumentNode | TypedDocumentNode<TData, TVariables>, options?: SkipToken | SuspenseQueryHookOptions<NoInfer<TData>, NoInfer<TVariables>>): UseSuspenseQueryResult<TData | undefined, TVariables>;
export declare function toApolloError(result: ApolloQueryResult<any>): ApolloError | undefined;
interface UseWatchQueryOptionsHookOptions<TData, TVariables extends OperationVariables> {
client: ApolloClient<unknown>;
query: DocumentNode | TypedDocumentNode<TData, TVariables>;
options: SkipToken | SuspenseQueryHookOptions<TData, TVariables>;
}
export declare function useWatchQueryOptions<TData, TVariables extends OperationVariables>({ client, query, options, }: UseWatchQueryOptionsHookOptions<TData, TVariables>): WatchQueryOptions<TVariables, TData>;
export {};
//# sourceMappingURL=useSuspenseQuery.d.ts.map

View File

@@ -0,0 +1,131 @@
import { __assign, __spreadArray } from "tslib";
import * as React from "rehackt";
import { invariant } from "../../utilities/globals/index.js";
import { ApolloError, NetworkStatus } from "../../core/index.js";
import { isNonEmptyArray } from "../../utilities/index.js";
import { useApolloClient } from "./useApolloClient.js";
import { DocumentType, verifyDocumentType } from "../parser/index.js";
import { __use, useDeepMemo } from "./internal/index.js";
import { getSuspenseCache } from "../internal/index.js";
import { canonicalStringify } from "../../cache/index.js";
import { skipToken } from "./constants.js";
export function useSuspenseQuery(query, options) {
if (options === void 0) { options = Object.create(null); }
var client = useApolloClient(options.client);
var suspenseCache = getSuspenseCache(client);
var watchQueryOptions = useWatchQueryOptions({
client: client,
query: query,
options: options,
});
var fetchPolicy = watchQueryOptions.fetchPolicy, variables = watchQueryOptions.variables;
var _a = options.queryKey, queryKey = _a === void 0 ? [] : _a;
var cacheKey = __spreadArray([
query,
canonicalStringify(variables)
], [].concat(queryKey), true);
var queryRef = suspenseCache.getQueryRef(cacheKey, function () {
return client.watchQuery(watchQueryOptions);
});
var _b = React.useState([queryRef.key, queryRef.promise]), current = _b[0], setPromise = _b[1];
// This saves us a re-execution of the render function when a variable changed.
if (current[0] !== queryRef.key) {
current[0] = queryRef.key;
current[1] = queryRef.promise;
}
var promise = current[1];
if (queryRef.didChangeOptions(watchQueryOptions)) {
current[1] = promise = queryRef.applyOptions(watchQueryOptions);
}
React.useEffect(function () {
var dispose = queryRef.retain();
var removeListener = queryRef.listen(function (promise) {
setPromise([queryRef.key, promise]);
});
return function () {
removeListener();
dispose();
};
}, [queryRef]);
var skipResult = React.useMemo(function () {
var error = toApolloError(queryRef.result);
return {
loading: false,
data: queryRef.result.data,
networkStatus: error ? NetworkStatus.error : NetworkStatus.ready,
error: error,
};
}, [queryRef.result]);
var result = fetchPolicy === "standby" ? skipResult : __use(promise);
var fetchMore = React.useCallback((function (options) {
var promise = queryRef.fetchMore(options);
setPromise([queryRef.key, queryRef.promise]);
return promise;
}), [queryRef]);
var refetch = React.useCallback(function (variables) {
var promise = queryRef.refetch(variables);
setPromise([queryRef.key, queryRef.promise]);
return promise;
}, [queryRef]);
var subscribeToMore = React.useCallback(function (options) { return queryRef.observable.subscribeToMore(options); }, [queryRef]);
return React.useMemo(function () {
return {
client: client,
data: result.data,
error: toApolloError(result),
networkStatus: result.networkStatus,
fetchMore: fetchMore,
refetch: refetch,
subscribeToMore: subscribeToMore,
};
}, [client, fetchMore, refetch, result, subscribeToMore]);
}
function validateOptions(options) {
var query = options.query, fetchPolicy = options.fetchPolicy, returnPartialData = options.returnPartialData;
verifyDocumentType(query, DocumentType.Query);
validateFetchPolicy(fetchPolicy);
validatePartialDataReturn(fetchPolicy, returnPartialData);
}
function validateFetchPolicy(fetchPolicy) {
if (fetchPolicy === void 0) { fetchPolicy = "cache-first"; }
var supportedFetchPolicies = [
"cache-first",
"network-only",
"no-cache",
"cache-and-network",
];
invariant(supportedFetchPolicies.includes(fetchPolicy), 56, fetchPolicy);
}
function validatePartialDataReturn(fetchPolicy, returnPartialData) {
if (fetchPolicy === "no-cache" && returnPartialData) {
globalThis.__DEV__ !== false && invariant.warn(57);
}
}
export function toApolloError(result) {
return isNonEmptyArray(result.errors) ?
new ApolloError({ graphQLErrors: result.errors })
: result.error;
}
export function useWatchQueryOptions(_a) {
var client = _a.client, query = _a.query, options = _a.options;
return useDeepMemo(function () {
var _a;
if (options === skipToken) {
return { query: query, fetchPolicy: "standby" };
}
var fetchPolicy = options.fetchPolicy ||
((_a = client.defaultOptions.watchQuery) === null || _a === void 0 ? void 0 : _a.fetchPolicy) ||
"cache-first";
var watchQueryOptions = __assign(__assign({}, options), { fetchPolicy: fetchPolicy, query: query, notifyOnNetworkStatusChange: false, nextFetchPolicy: void 0 });
if (globalThis.__DEV__ !== false) {
validateOptions(watchQueryOptions);
}
// Assign the updated fetch policy after our validation since `standby` is
// not a supported fetch policy on its own without the use of `skip`.
if (options.skip) {
watchQueryOptions.fetchPolicy = "standby";
}
return watchQueryOptions;
}, [client, options, query]);
}
//# sourceMappingURL=useSuspenseQuery.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,4 @@
type RealUseSESHookType = typeof import("use-sync-external-store").useSyncExternalStore;
export declare const useSyncExternalStore: RealUseSESHookType;
export {};
//# sourceMappingURL=useSyncExternalStore.d.ts.map

View File

@@ -0,0 +1,103 @@
import { invariant } from "../../utilities/globals/index.js";
import * as React from "rehackt";
import { canUseLayoutEffect } from "../../utilities/index.js";
var didWarnUncachedGetSnapshot = false;
// Prevent webpack from complaining about our feature detection of the
// useSyncExternalStore property of the React namespace, which is expected not
// to exist when using React 17 and earlier, and that's fine.
var uSESKey = "useSyncExternalStore";
var realHook = React[uSESKey];
// Adapted from https://www.npmjs.com/package/use-sync-external-store, with
// Apollo Client deviations called out by "// DEVIATION ..." comments.
// When/if React.useSyncExternalStore is defined, delegate fully to it.
export var useSyncExternalStore = realHook ||
(function (subscribe, getSnapshot, getServerSnapshot) {
// Read the current snapshot from the store on every render. Again, this
// breaks the rules of React, and only works here because of specific
// implementation details, most importantly that updates are
// always synchronous.
var value = getSnapshot();
if (
// DEVIATION: Using __DEV__
globalThis.__DEV__ !== false &&
!didWarnUncachedGetSnapshot &&
// DEVIATION: Not using Object.is because we know our snapshots will never
// be exotic primitive values like NaN, which is !== itself.
value !== getSnapshot()) {
didWarnUncachedGetSnapshot = true;
// DEVIATION: Using invariant.error instead of console.error directly.
globalThis.__DEV__ !== false && invariant.error(58);
}
// Because updates are synchronous, we don't queue them. Instead we force a
// re-render whenever the subscribed state changes by updating an some
// arbitrary useState hook. Then, during render, we call getSnapshot to read
// the current value.
//
// Because we don't actually use the state returned by the useState hook, we
// can save a bit of memory by storing other stuff in that slot.
//
// To implement the early bailout, we need to track some things on a mutable
// object. Usually, we would put that in a useRef hook, but we can stash it in
// our useState hook instead.
//
// To force a re-render, we call forceUpdate({inst}). That works because the
// new object always fails an equality check.
var _a = React.useState({
inst: { value: value, getSnapshot: getSnapshot },
}), inst = _a[0].inst, forceUpdate = _a[1];
// Track the latest getSnapshot function with a ref. This needs to be updated
// in the layout phase so we can access it during the tearing check that
// happens on subscribe.
if (canUseLayoutEffect) {
// DEVIATION: We avoid calling useLayoutEffect when !canUseLayoutEffect,
// which may seem like a conditional hook, but this code ends up behaving
// unconditionally (one way or the other) because canUseLayoutEffect is
// constant.
React.useLayoutEffect(function () {
Object.assign(inst, { value: value, getSnapshot: getSnapshot });
// Whenever getSnapshot or subscribe changes, we need to check in the
// commit phase if there was an interleaved mutation. In concurrent mode
// this can happen all the time, but even in synchronous mode, an earlier
// effect may have mutated the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
}, [subscribe, value, getSnapshot]);
}
else {
Object.assign(inst, { value: value, getSnapshot: getSnapshot });
}
React.useEffect(function () {
// Check for changes right before subscribing. Subsequent changes will be
// detected in the subscription handler.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
// Subscribe to the store and return a clean-up function.
return subscribe(function handleStoreChange() {
// TODO: Because there is no cross-renderer API for batching updates, it's
// up to the consumer of this library to wrap their subscription event
// with unstable_batchedUpdates. Should we try to detect when this isn't
// the case and print a warning in development?
// The store changed. Check if the snapshot changed since the last time we
// read from the store.
if (checkIfSnapshotChanged(inst)) {
// Force a re-render.
forceUpdate({ inst: inst });
}
});
}, [subscribe]);
return value;
});
function checkIfSnapshotChanged(_a) {
var value = _a.value, getSnapshot = _a.getSnapshot;
try {
return value !== getSnapshot();
}
catch (_b) {
return true;
}
}
//# sourceMappingURL=useSyncExternalStore.js.map

File diff suppressed because one or more lines are too long