UNPKG

2.98 kBJavaScriptView Raw
1import { __assign, __rest } from "tslib";
2import * as React from "rehackt";
3import { mergeDeepArray } from "../../utilities/index.js";
4import { useApolloClient } from "./useApolloClient.js";
5import { useSyncExternalStore } from "./useSyncExternalStore.js";
6import { useDeepMemo, useLazyRef, wrapHook } from "./internal/index.js";
7import equal from "@wry/equality";
8export function useFragment(options) {
9 return wrapHook("useFragment", _useFragment, useApolloClient(options.client))(options);
10}
11function _useFragment(options) {
12 var cache = useApolloClient(options.client).cache;
13 var diffOptions = useDeepMemo(function () {
14 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"]);
15 return __assign(__assign({}, rest), { returnPartialData: true, id: typeof from === "string" ? from : cache.identify(from), query: cache["getFragmentDoc"](fragment, fragmentName), optimistic: optimistic });
16 }, [options]);
17 var resultRef = useLazyRef(function () {
18 return diffToResult(cache.diff(diffOptions));
19 });
20 var stableOptions = useDeepMemo(function () { return options; }, [options]);
21 // Since .next is async, we need to make sure that we
22 // get the correct diff on the next render given new diffOptions
23 React.useMemo(function () {
24 resultRef.current = diffToResult(cache.diff(diffOptions));
25 }, [diffOptions, cache]);
26 // Used for both getSnapshot and getServerSnapshot
27 var getSnapshot = React.useCallback(function () { return resultRef.current; }, []);
28 return useSyncExternalStore(React.useCallback(function (forceUpdate) {
29 var lastTimeout = 0;
30 var subscription = cache.watchFragment(stableOptions).subscribe({
31 next: function (result) {
32 if (equal(result, resultRef.current))
33 return;
34 resultRef.current = result;
35 // If we get another update before we've re-rendered, bail out of
36 // the update and try again. This ensures that the relative timing
37 // between useQuery and useFragment stays roughly the same as
38 // fixed in https://github.com/apollographql/apollo-client/pull/11083
39 clearTimeout(lastTimeout);
40 lastTimeout = setTimeout(forceUpdate);
41 },
42 });
43 return function () {
44 subscription.unsubscribe();
45 clearTimeout(lastTimeout);
46 };
47 }, [cache, stableOptions]), getSnapshot, getSnapshot);
48}
49function diffToResult(diff) {
50 var result = {
51 data: diff.result,
52 complete: !!diff.complete,
53 };
54 if (diff.missing) {
55 result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
56 }
57 return result;
58}
59//# sourceMappingURL=useFragment.js.map
\No newline at end of file