1 | import { __assign, __rest } from "tslib";
|
2 | import { useRef } from "react";
|
3 | import { equal } from "@wry/equality";
|
4 | import { mergeDeepArray } from "../../utilities/index.js";
|
5 | import { useApolloClient } from "./useApolloClient.js";
|
6 | import { useSyncExternalStore } from "./useSyncExternalStore.js";
|
7 | export function useFragment_experimental(options) {
|
8 | var cache = useApolloClient().cache;
|
9 | 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"]);
|
10 | var diffOptions = __assign(__assign({}, rest), { id: typeof from === "string" ? from : cache.identify(from), query: cache["getFragmentDoc"](fragment, fragmentName), optimistic: optimistic });
|
11 | var resultRef = useRef();
|
12 | var latestDiff = cache.diff(diffOptions);
|
13 | var getSnapshot = function () {
|
14 | var latestDiffToResult = diffToResult(latestDiff);
|
15 | return resultRef.current &&
|
16 | equal(resultRef.current.data, latestDiffToResult.data)
|
17 | ? resultRef.current
|
18 | : (resultRef.current = latestDiffToResult);
|
19 | };
|
20 | return useSyncExternalStore(function (forceUpdate) {
|
21 | return cache.watch(__assign(__assign({}, diffOptions), { immediate: true, callback: function (diff) {
|
22 | if (!equal(diff, latestDiff)) {
|
23 | resultRef.current = diffToResult((latestDiff = diff));
|
24 | forceUpdate();
|
25 | }
|
26 | } }));
|
27 | }, getSnapshot, getSnapshot);
|
28 | }
|
29 | function diffToResult(diff) {
|
30 | var result = {
|
31 | data: diff.result,
|
32 | complete: !!diff.complete,
|
33 | };
|
34 | if (diff.missing) {
|
35 | result.missing = mergeDeepArray(diff.missing.map(function (error) { return error.missing; }));
|
36 | }
|
37 | return result;
|
38 | }
|
39 |
|
\ | No newline at end of file |