@data-client/vue 0.18.0 → 0.18.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/CHANGELOG.md +381 -1
  2. package/README.md +86 -41
  3. package/dist/index.js +223 -158
  4. package/dist/index.umd.min.js +1 -1
  5. package/lib/consumers/refetchTriggers.d.ts +12 -0
  6. package/lib/consumers/refetchTriggers.d.ts.map +1 -0
  7. package/lib/consumers/refetchTriggers.js +9 -0
  8. package/lib/consumers/useCache.d.ts +1 -1
  9. package/lib/consumers/useCache.d.ts.map +1 -1
  10. package/lib/consumers/useCache.js +3 -53
  11. package/lib/consumers/useCacheResponse.d.ts +20 -0
  12. package/lib/consumers/useCacheResponse.d.ts.map +1 -0
  13. package/lib/consumers/useCacheResponse.js +55 -0
  14. package/lib/consumers/useCountRef.d.ts +7 -0
  15. package/lib/consumers/useCountRef.d.ts.map +1 -0
  16. package/lib/consumers/useCountRef.js +10 -0
  17. package/lib/consumers/useDLE.d.ts +1 -1
  18. package/lib/consumers/useDLE.d.ts.map +1 -1
  19. package/lib/consumers/useDLE.js +16 -62
  20. package/lib/consumers/useDebounce.d.ts +1 -1
  21. package/lib/consumers/useDebounce.d.ts.map +1 -1
  22. package/lib/consumers/useDebounce.js +1 -2
  23. package/lib/consumers/useExpired.d.ts +12 -0
  24. package/lib/consumers/useExpired.d.ts.map +1 -0
  25. package/lib/consumers/useExpired.js +19 -0
  26. package/lib/consumers/useFetch.d.ts +8 -11
  27. package/lib/consumers/useFetch.d.ts.map +1 -1
  28. package/lib/consumers/useFetch.js +13 -24
  29. package/lib/consumers/useLive.js +1 -1
  30. package/lib/consumers/useLoading.d.ts +1 -1
  31. package/lib/consumers/useLoading.d.ts.map +1 -1
  32. package/lib/consumers/useLoading.js +1 -2
  33. package/lib/consumers/useQuery.d.ts +1 -1
  34. package/lib/consumers/useQuery.d.ts.map +1 -1
  35. package/lib/consumers/useQuery.js +6 -12
  36. package/lib/consumers/useResponseMeta.d.ts +23 -0
  37. package/lib/consumers/useResponseMeta.d.ts.map +1 -0
  38. package/lib/consumers/useResponseMeta.js +36 -0
  39. package/lib/consumers/useSubscription.js +4 -4
  40. package/lib/consumers/useSuspense.d.ts +1 -1
  41. package/lib/consumers/useSuspense.d.ts.map +1 -1
  42. package/lib/consumers/useSuspense.js +58 -34
  43. package/lib/context.d.ts +1 -1
  44. package/lib/context.d.ts.map +1 -1
  45. package/lib/context.js +3 -3
  46. package/lib/index.d.ts +2 -1
  47. package/lib/index.d.ts.map +1 -1
  48. package/lib/index.js +4 -2
  49. package/lib/internal.d.ts +6 -0
  50. package/lib/internal.d.ts.map +1 -0
  51. package/lib/internal.js +6 -0
  52. package/lib/providers/DataClientPlugin.d.ts +1 -1
  53. package/lib/providers/DataClientPlugin.d.ts.map +1 -1
  54. package/lib/providers/DataClientPlugin.js +16 -4
  55. package/lib/providers/createDataClient.d.ts +10 -4
  56. package/lib/providers/createDataClient.d.ts.map +1 -1
  57. package/lib/providers/createDataClient.js +11 -5
  58. package/lib/providers/getDefaultManagers.d.ts.map +1 -1
  59. package/lib/providers/getDefaultManagers.js +1 -1
  60. package/lib/providers/index.d.ts +2 -1
  61. package/lib/providers/index.d.ts.map +1 -1
  62. package/lib/providers/index.js +1 -1
  63. package/lib/test/MockPlugin.d.ts +1 -1
  64. package/lib/test/MockPlugin.d.ts.map +1 -1
  65. package/lib/test/MockPlugin.js +1 -1
  66. package/lib/test/index.d.ts +2 -1
  67. package/lib/test/index.d.ts.map +1 -1
  68. package/lib/test/index.js +1 -1
  69. package/lib/test/mountDataClient.d.ts +5 -3
  70. package/lib/test/mountDataClient.d.ts.map +1 -1
  71. package/lib/test/mountDataClient.js +15 -10
  72. package/lib/test/renderDataCompose.d.ts +10 -4
  73. package/lib/test/renderDataCompose.d.ts.map +1 -1
  74. package/lib/test/renderDataCompose.js +2 -3
  75. package/package.json +21 -6
  76. package/src/__tests__/__snapshots__/context.test.ts.snap +2 -2
  77. package/src/__tests__/context.test.ts +1 -1
  78. package/src/__tests__/integration-garbage-collection.web.ts +80 -4
  79. package/src/__tests__/useCache.web.ts +160 -93
  80. package/src/__tests__/useDLE.web.ts +204 -96
  81. package/src/__tests__/useFetch.web.ts +100 -37
  82. package/src/__tests__/useQuery.web.ts +60 -50
  83. package/src/__tests__/useSubscription.web.ts +74 -75
  84. package/src/__tests__/useSuspense.web.ts +455 -46
  85. package/src/consumers/refetchTriggers.ts +22 -0
  86. package/src/consumers/useCache.ts +7 -70
  87. package/src/consumers/useCacheResponse.ts +56 -0
  88. package/src/consumers/useCountRef.ts +15 -0
  89. package/src/consumers/useDLE.ts +24 -83
  90. package/src/consumers/useDebounce.ts +2 -1
  91. package/src/consumers/useExpired.ts +26 -0
  92. package/src/consumers/useFetch.ts +34 -49
  93. package/src/consumers/useLive.ts +1 -1
  94. package/src/consumers/useLoading.ts +2 -1
  95. package/src/consumers/useQuery.ts +10 -13
  96. package/src/consumers/useResponseMeta.ts +41 -0
  97. package/src/consumers/useSubscription.ts +3 -3
  98. package/src/consumers/useSuspense.ts +66 -58
  99. package/src/context.ts +4 -3
  100. package/src/index.ts +7 -1
  101. package/src/internal.ts +12 -0
  102. package/src/providers/DataClientPlugin.ts +17 -3
  103. package/src/providers/__tests__/DataClientPlugin.test.ts +40 -1
  104. package/src/providers/createDataClient.ts +15 -5
  105. package/src/providers/getDefaultManagers.ts +2 -6
  106. package/src/providers/index.ts +2 -5
  107. package/src/test/MockPlugin.ts +3 -3
  108. package/src/test/README.md +10 -304
  109. package/src/test/__tests__/mountDataClient.test.ts +38 -0
  110. package/src/test/index.ts +2 -1
  111. package/src/test/mountDataClient.ts +22 -17
  112. package/src/test/renderDataCompose.ts +11 -7
@@ -0,0 +1,56 @@
1
+ import { ExpiryStatus } from '@data-client/core';
2
+ import { computed } from 'vue';
3
+
4
+ import useExpired from './useExpired.js';
5
+ import useResponseMeta from './useResponseMeta.js';
6
+
7
+ /** Reactive store response shared by useCache() and useDLE().
8
+ *
9
+ * `data` excludes cached entities while useSuspense() would suspend.
10
+ */
11
+ export default function useCacheResponse(endpoint: any, args: any[]) {
12
+ const { controller, stateRef, resolvedArgs, argsKey, responseMeta } =
13
+ useResponseMeta(endpoint, args);
14
+
15
+ // If we are hard invalid we must fetch regardless of triggering or staleness
16
+ const forceFetch = computed(
17
+ () => responseMeta.value.expiryStatus === ExpiryStatus.Invalid,
18
+ );
19
+
20
+ /*********** This block is to ensure results are only filled when they would not suspend **************/
21
+ // This computation reflects the behavior of useSuspense/useFetch
22
+ // It only changes the value when expiry or params change.
23
+ // This way, random unrelated re-renders don't cause the concept of expiry
24
+ // to change
25
+ const expired = useExpired(responseMeta, stateRef, argsKey, forceFetch);
26
+
27
+ // fully "valid" data will not suspend/loading even if it is not fresh
28
+ const loading = computed(
29
+ () =>
30
+ responseMeta.value.expiryStatus !== ExpiryStatus.Valid && expired.value,
31
+ );
32
+ /****************************************************************************************************/
33
+
34
+ const data = computed(() => {
35
+ // if useSuspense() would suspend, don't include entities from cache
36
+ if (loading.value) {
37
+ if (!endpoint.schema) return undefined;
38
+ // TODO: use getResponse() once it just returns data
39
+ return controller.getResponseMeta(endpoint, ...resolvedArgs.value, {
40
+ ...stateRef.value,
41
+ entities: {},
42
+ }).data;
43
+ }
44
+ return responseMeta.value.data;
45
+ });
46
+
47
+ return {
48
+ controller,
49
+ stateRef,
50
+ resolvedArgs,
51
+ argsKey,
52
+ responseMeta,
53
+ loading,
54
+ data,
55
+ };
56
+ }
@@ -0,0 +1,15 @@
1
+ import { watch } from 'vue';
2
+ import type { Ref } from 'vue';
3
+
4
+ /** Keeps a store response's entities from being garbage collected while mounted. */
5
+ export default function useCountRef(
6
+ meta: Ref<{ data: unknown; countRef: () => () => void }>,
7
+ ) {
8
+ watch(
9
+ () => meta.value.data,
10
+ (_newVal, _oldVal, onCleanup) => {
11
+ onCleanup(meta.value.countRef());
12
+ },
13
+ { immediate: true },
14
+ );
15
+ }
@@ -7,14 +7,16 @@ import type {
7
7
  Schema,
8
8
  ResolveType,
9
9
  } from '@data-client/core';
10
- import { ExpiryStatus } from '@data-client/core';
11
- import { computed, unref, watch, markRaw, type ComputedRef } from 'vue';
10
+ import { computed, watch, markRaw } from 'vue';
11
+ import type { ComputedRef } from 'vue';
12
12
 
13
- import { useController, injectState } from '../context.js';
14
13
  import type {
15
14
  MaybeRefsOrGetters,
16
15
  MaybeRefsOrGettersNullable,
17
16
  } from '../types.js';
17
+ import refetchTriggers from './refetchTriggers.js';
18
+ import useCacheResponse from './useCacheResponse.js';
19
+ import { isStale } from './useResponseMeta.js';
18
20
 
19
21
  /**
20
22
  * Use async data with { data, loading, error } (DLE)
@@ -56,97 +58,36 @@ export default function useDLE<
56
58
  error: ComputedRef<ErrorTypes | undefined>;
57
59
  };
58
60
 
59
- export default function useDLE(endpoint: any, ...args: any[]): any {
60
- const stateRef = injectState();
61
- const controller = useController();
62
-
63
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
64
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
65
-
66
- // Compute a key that changes when args change (including reactive props)
67
- const argsKey = computed(() =>
68
- resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
69
- );
70
-
71
- // Compute response meta reactively so we can respond to store updates
72
- const responseMeta = computed(() => {
73
- return controller.getResponseMeta(
74
- endpoint,
75
- ...resolvedArgs.value,
76
- stateRef.value,
77
- );
78
- });
79
-
80
- // If we are hard invalid we must fetch regardless of triggering or staleness
81
- const forceFetch = computed(
82
- () => responseMeta.value.expiryStatus === ExpiryStatus.Invalid,
83
- );
84
-
85
- /*********** This block is to ensure results are only filled when they would not suspend **************/
86
- // This computation reflects the behavior of useSuspense/useFetch
87
- // It only changes the value when expiry or params change.
88
- // This way, random unrelated re-renders don't cause the concept of expiry
89
- // to change
90
- const expired = computed(() => {
91
- return !!(
92
- (Date.now() > responseMeta.value.expiresAt || forceFetch.value) &&
93
- argsKey.value
94
- );
95
- });
96
-
97
- // fully "valid" data will not suspend/loading even if it is not fresh
98
- const loading = computed(() => {
99
- return !!(
100
- responseMeta.value.expiryStatus !== ExpiryStatus.Valid && expired.value
101
- );
102
- });
103
- /****************************************************************************************************/
61
+ export default function useDLE(
62
+ endpoint: any,
63
+ ...args: any[]
64
+ ): {
65
+ data: ComputedRef<unknown>;
66
+ loading: ComputedRef<boolean>;
67
+ error: ComputedRef<ErrorTypes | undefined>;
68
+ } {
69
+ const {
70
+ controller,
71
+ stateRef,
72
+ resolvedArgs,
73
+ argsKey,
74
+ responseMeta,
75
+ loading,
76
+ data,
77
+ } = useCacheResponse(endpoint, args);
104
78
 
105
79
  // Trigger fetch when necessary
106
80
  watch(
107
- () => {
108
- const m = responseMeta.value;
109
- return [
110
- m.expiresAt,
111
- m.expiryStatus,
112
- stateRef.value.lastReset,
113
- argsKey.value,
114
- ];
115
- },
81
+ refetchTriggers(responseMeta, stateRef, argsKey),
116
82
  async () => {
117
83
  const currentKey = argsKey.value;
118
84
  if (!currentKey) return;
119
- const meta = responseMeta.value;
120
- const force = forceFetch.value;
121
- if (Date.now() <= meta.expiresAt && !force) return;
85
+ if (!isStale(responseMeta.value)) return;
122
86
  await controller.fetch(endpoint, ...resolvedArgs.value).catch(() => {});
123
87
  },
124
88
  { immediate: true },
125
89
  );
126
90
 
127
- // Maintain GC refcounts on data mount/changes
128
- watch(
129
- () => responseMeta.value.data,
130
- (_newVal, _oldVal, onCleanup) => {
131
- const decrement = responseMeta.value.countRef();
132
- onCleanup(() => decrement());
133
- },
134
- { immediate: true },
135
- );
136
-
137
- const data = computed(() => {
138
- // if useSuspense() would suspend, don't include entities from cache
139
- if (loading.value) {
140
- if (!endpoint.schema) return undefined;
141
- // TODO: use getResponse() once it just returns data
142
- return controller.getResponseMeta(endpoint, ...resolvedArgs.value, {
143
- ...stateRef.value,
144
- entities: {},
145
- }).data as any;
146
- }
147
- return responseMeta.value.data;
148
- });
149
-
150
91
  const error = computed(() => {
151
92
  return controller.getError(endpoint, ...resolvedArgs.value, stateRef.value);
152
93
  });
@@ -1,4 +1,5 @@
1
- import { ref, watch, onUnmounted, type Ref } from 'vue';
1
+ import { ref, watch, onUnmounted } from 'vue';
2
+ import type { Ref } from 'vue';
2
3
 
3
4
  /**
4
5
  * Keeps value updated after delay time
@@ -0,0 +1,26 @@
1
+ import type { State } from '@data-client/core';
2
+ import { computed } from 'vue';
3
+ import type { ComputedRef, Ref } from 'vue';
4
+
5
+ /** Whether the response is expired, re-checked only when expiry, args, or a reset changes.
6
+ *
7
+ * Mirrors the useMemo deps in @data-client/react so unrelated store updates
8
+ * don't re-read Date.now(). Relies on Vue >=3.4 computed stability: the narrow
9
+ * computeds below don't notify `expired` when their value is unchanged.
10
+ */
11
+ export default function useExpired(
12
+ responseMeta: Readonly<Ref<{ readonly expiresAt: number }>>,
13
+ stateRef: Readonly<Ref<State<unknown>>>,
14
+ argsKey: Readonly<Ref<string>>,
15
+ forceFetch: Readonly<Ref<boolean>>,
16
+ ): ComputedRef<boolean> {
17
+ const expiresAt = computed(() => responseMeta.value.expiresAt);
18
+ const lastReset = computed(() => stateRef.value.lastReset);
19
+ return computed(() => {
20
+ // read every source up front so short-circuiting doesn't drop tracking
21
+ const key = argsKey.value;
22
+ const force = forceFetch.value;
23
+ void lastReset.value;
24
+ return !!((Date.now() > expiresAt.value || force) && key);
25
+ });
26
+ }
@@ -1,20 +1,22 @@
1
- import { ExpiryStatus } from '@data-client/core';
2
1
  import type {
3
2
  EndpointInterface,
4
3
  Denormalize,
5
4
  Schema,
6
5
  FetchFunction,
7
6
  DenormalizeNullable,
7
+ ResolveType,
8
8
  } from '@data-client/core';
9
- import { computed, watch, ref, unref } from 'vue';
9
+ import { watch, ref } from 'vue';
10
+ import type { Ref } from 'vue';
10
11
 
11
- import { useController, injectState } from '../context.js';
12
12
  import type {
13
13
  MaybeRefsOrGetters,
14
14
  MaybeRefsOrGettersNullable,
15
15
  } from '../types.js';
16
+ import refetchTriggers from './refetchTriggers.js';
17
+ import useResponseMeta, { isStale } from './useResponseMeta.js';
16
18
 
17
- type FetchPromise = Promise<any> & { resolved: boolean };
19
+ type FetchPromise<T = any> = Promise<T> & { resolved: boolean };
18
20
 
19
21
  const RESOLVED = Object.assign(Promise.resolve(), {
20
22
  resolved: true,
@@ -43,8 +45,14 @@ export default function useFetch<
43
45
  >(
44
46
  endpoint: E,
45
47
  ...args: MaybeRefsOrGetters<Parameters<E>>
46
- ): E['schema'] extends undefined | null ? ReturnType<E> & { resolved: boolean }
47
- : Promise<Denormalize<E['schema']>> & { resolved: boolean };
48
+ ): Readonly<
49
+ Ref<
50
+ FetchPromise<
51
+ E['schema'] extends undefined | null ? ResolveType<E>
52
+ : Denormalize<E['schema']>
53
+ >
54
+ >
55
+ >;
48
56
 
49
57
  export default function useFetch<
50
58
  E extends EndpointInterface<
@@ -55,31 +63,22 @@ export default function useFetch<
55
63
  >(
56
64
  endpoint: E,
57
65
  ...args: MaybeRefsOrGettersNullable<Parameters<E>> | readonly [null]
58
- ): E['schema'] extends undefined | null ?
59
- (ReturnType<E> & { resolved: boolean }) | undefined
60
- : | (Promise<DenormalizeNullable<E['schema']>> & { resolved: boolean })
61
- | undefined;
62
-
63
- export default function useFetch(endpoint: any, ...args: any[]): any {
64
- const stateRef = injectState();
65
- const controller = useController();
66
-
67
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
68
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
69
-
70
- // Compute a key that changes when args change (including reactive props)
71
- const argsKey = computed(() =>
72
- resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
73
- );
74
-
75
- // Compute response meta reactively so we can respond to store updates
76
- const responseMeta = computed(() => {
77
- return controller.getResponseMeta(
78
- endpoint,
79
- ...resolvedArgs.value,
80
- stateRef.value,
81
- );
82
- });
66
+ ): Readonly<
67
+ Ref<
68
+ | FetchPromise<
69
+ E['schema'] extends undefined | null ? ResolveType<E>
70
+ : DenormalizeNullable<E['schema']>
71
+ >
72
+ | undefined
73
+ >
74
+ >;
75
+
76
+ export default function useFetch(
77
+ endpoint: any,
78
+ ...args: any[]
79
+ ): Readonly<Ref<FetchPromise | undefined>> {
80
+ const { controller, stateRef, resolvedArgs, argsKey, responseMeta } =
81
+ useResponseMeta(endpoint, args);
83
82
 
84
83
  const lastPromise = ref<FetchPromise | undefined>(undefined);
85
84
  let lastKey = '';
@@ -91,10 +90,7 @@ export default function useFetch(endpoint: any, ...args: any[]): any {
91
90
  lastKey = '';
92
91
  return;
93
92
  }
94
- const meta = responseMeta.value;
95
- const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
96
-
97
- if (Date.now() > meta.expiresAt || forceFetch) {
93
+ if (isStale(responseMeta.value)) {
98
94
  lastPromise.value = trackPromise(
99
95
  controller.fetch(endpoint, ...resolvedArgs.value),
100
96
  );
@@ -109,20 +105,9 @@ export default function useFetch(endpoint: any, ...args: any[]): any {
109
105
  maybeFetch();
110
106
 
111
107
  // Also watch for store changes that might require refetch (e.g., invalidation)
112
- watch(
113
- () => {
114
- const m = responseMeta.value;
115
- return [
116
- m.expiresAt,
117
- m.expiryStatus,
118
- stateRef.value.lastReset,
119
- argsKey.value,
120
- ];
121
- },
122
- () => {
123
- maybeFetch();
124
- },
125
- );
108
+ watch(refetchTriggers(responseMeta, stateRef, argsKey), () => {
109
+ maybeFetch();
110
+ });
126
111
 
127
112
  return lastPromise;
128
113
  }
@@ -62,7 +62,7 @@ export default function useLive<
62
62
  export default async function useLive(
63
63
  endpoint: any,
64
64
  ...args: any[]
65
- ): Promise<any> {
65
+ ): Promise<DeepReadonly<ComputedRef<unknown>>> {
66
66
  useSubscription(endpoint, ...args);
67
67
  return useSuspense(endpoint, ...args);
68
68
  }
@@ -1,4 +1,5 @@
1
- import { ref, onUnmounted, type Ref } from 'vue';
1
+ import { ref, onUnmounted } from 'vue';
2
+ import type { Ref } from 'vue';
2
3
 
3
4
  /**
4
5
  * Takes an async function and tracks resolution as a boolean.
@@ -3,10 +3,12 @@ import type {
3
3
  Queryable,
4
4
  SchemaArgs,
5
5
  } from '@data-client/core';
6
- import { computed, unref, watch, type ComputedRef } from 'vue';
6
+ import { computed, toValue } from 'vue';
7
+ import type { ComputedRef } from 'vue';
7
8
 
8
9
  import { useController, injectState } from '../context.js';
9
10
  import type { MaybeRefsOrGetters } from '../types.js';
11
+ import useCountRef from './useCountRef.js';
10
12
 
11
13
  /**
12
14
  * Query the store.
@@ -19,12 +21,15 @@ export default function useQuery<S extends Queryable>(
19
21
  ...args: MaybeRefsOrGetters<SchemaArgs<S>>
20
22
  ): ComputedRef<DenormalizeNullable<S> | undefined>;
21
23
 
22
- export default function useQuery(schema: any, ...args: any[]): any {
24
+ export default function useQuery(
25
+ schema: any,
26
+ ...args: any[]
27
+ ): ComputedRef<unknown> {
23
28
  const stateRef = injectState();
24
29
  const controller = useController();
25
30
 
26
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
27
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
31
+ // Track top-level reactive args (refs and getters are resolved). This allows props/refs/getters to trigger updates.
32
+ const resolvedArgs = computed(() => args.map(a => toValue(a)) as any);
28
33
 
29
34
  // Compute query meta based on state and args. This mirrors React's memoization
30
35
  // that keys off state.entities/indexes and args.
@@ -36,15 +41,7 @@ export default function useQuery(schema: any, ...args: any[]): any {
36
41
  ),
37
42
  );
38
43
 
39
- // Maintain GC refcounts on data mount/changes
40
- watch(
41
- () => queryMeta.value.data,
42
- (_newVal, _oldVal, onCleanup) => {
43
- const decrement = queryMeta.value.countRef();
44
- onCleanup(() => decrement());
45
- },
46
- { immediate: true },
47
- );
44
+ useCountRef(queryMeta);
48
45
 
49
46
  return computed(() => queryMeta.value.data);
50
47
  }
@@ -0,0 +1,41 @@
1
+ import { ExpiryStatus } from '@data-client/core';
2
+ import { computed, toValue } from 'vue';
3
+
4
+ import { useController, injectState } from '../context.js';
5
+ import useCountRef from './useCountRef.js';
6
+
7
+ /** Reactive store response for an endpoint and its (possibly reactive) args.
8
+ *
9
+ * Keeps the response's entities from being garbage collected while mounted.
10
+ */
11
+ export default function useResponseMeta(endpoint: any, args: any[]) {
12
+ const stateRef = injectState();
13
+ const controller = useController();
14
+
15
+ // Track top-level reactive args (refs and getters are resolved). This allows props/refs/getters to trigger updates.
16
+ const resolvedArgs = computed(() => args.map(a => toValue(a)) as any);
17
+
18
+ // Compute a key that changes when args change (including reactive props)
19
+ const argsKey = computed(() =>
20
+ resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
21
+ );
22
+
23
+ // Compute response meta reactively so we can respond to store updates
24
+ const responseMeta = computed(() =>
25
+ controller.getResponseMeta(endpoint, ...resolvedArgs.value, stateRef.value),
26
+ );
27
+
28
+ useCountRef(responseMeta);
29
+
30
+ return { controller, stateRef, resolvedArgs, argsKey, responseMeta };
31
+ }
32
+
33
+ /** Whether a response needs fetching; hard invalid data must refetch regardless of staleness */
34
+ export function isStale(meta: {
35
+ expiryStatus: ExpiryStatus;
36
+ expiresAt: number;
37
+ }) {
38
+ return (
39
+ meta.expiryStatus === ExpiryStatus.Invalid || Date.now() > meta.expiresAt
40
+ );
41
+ }
@@ -3,7 +3,7 @@ import type {
3
3
  Schema,
4
4
  FetchFunction,
5
5
  } from '@data-client/core';
6
- import { computed, unref, watch } from 'vue';
6
+ import { computed, toValue, watch } from 'vue';
7
7
 
8
8
  import { useController } from '../context.js';
9
9
  import type { MaybeRefsOrGettersNullable } from '../types.js';
@@ -25,8 +25,8 @@ export default function useSubscription<
25
25
  ) {
26
26
  const controller = useController();
27
27
 
28
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger resubscribe.
29
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
28
+ // Track top-level reactive args (refs and getters are resolved). This allows props/refs/getters to trigger resubscribe.
29
+ const resolvedArgs = computed(() => args.map(a => toValue(a)) as any);
30
30
  const key = computed(() => {
31
31
  if (resolvedArgs.value[0] === null) return '';
32
32
  return endpoint.key(...(resolvedArgs.value as readonly [...Parameters<E>]));
@@ -7,20 +7,15 @@ import type {
7
7
  DenormalizeNullable,
8
8
  ResolveType,
9
9
  } from '@data-client/core';
10
- import {
11
- computed,
12
- unref,
13
- watch,
14
- readonly,
15
- type DeepReadonly,
16
- type ComputedRef,
17
- } from 'vue';
10
+ import { computed, customRef, watch, readonly, shallowRef } from 'vue';
11
+ import type { DeepReadonly, ComputedRef } from 'vue';
18
12
 
19
- import { useController, injectState } from '../context.js';
20
13
  import type {
21
14
  MaybeRefsOrGetters,
22
15
  MaybeRefsOrGettersNullable,
23
16
  } from '../types.js';
17
+ import refetchTriggers from './refetchTriggers.js';
18
+ import useResponseMeta, { isStale } from './useResponseMeta.js';
24
19
 
25
20
  /**
26
21
  * Ensure an endpoint is available.
@@ -69,65 +64,78 @@ export default function useSuspense<
69
64
  export default async function useSuspense(
70
65
  endpoint: any,
71
66
  ...args: any[]
72
- ): Promise<any> {
73
- const stateRef = injectState();
74
- const controller = useController();
67
+ ): Promise<DeepReadonly<ComputedRef<unknown>>> {
68
+ const { controller, stateRef, resolvedArgs, argsKey, responseMeta } =
69
+ useResponseMeta(endpoint, args);
75
70
 
76
- // Track top-level reactive args (Refs are unwrapped). This allows props/refs to trigger updates.
77
- const resolvedArgs = computed(() => args.map(a => unref(a as any)) as any);
78
-
79
- // Compute a key that changes when args change (including reactive props)
80
- const argsKey = computed(() =>
81
- resolvedArgs.value[0] !== null ? endpoint.key(...resolvedArgs.value) : '',
82
- );
83
-
84
- // Compute response meta reactively so we can respond to store updates
85
- const responseMeta = computed(() => {
86
- return controller.getResponseMeta(
87
- endpoint,
88
- ...resolvedArgs.value,
89
- stateRef.value,
90
- );
91
- });
71
+ // key of the fetch in flight; staleness alone isn't reactive (time passes without a
72
+ // refetch), so only hold previous data while a fetch is actually running
73
+ const fetchingKey = shallowRef('');
92
74
 
93
75
  const maybeFetch = async () => {
94
76
  const currentKey = argsKey.value;
95
77
  if (!currentKey) return;
96
- const meta = responseMeta.value;
97
- const forceFetch = meta.expiryStatus === ExpiryStatus.Invalid;
98
- if (Date.now() <= meta.expiresAt && !forceFetch) return;
99
- await controller.fetch(endpoint, ...resolvedArgs.value);
78
+ if (!isStale(responseMeta.value)) return;
79
+ fetchingKey.value = currentKey;
80
+ try {
81
+ await controller.fetch(endpoint, ...resolvedArgs.value);
82
+ } finally {
83
+ // store updates synchronously before fetch resolves, so data is ready here
84
+ if (fetchingKey.value === currentKey) fetchingKey.value = '';
85
+ }
100
86
  };
101
87
 
102
88
  // Watch for changes to key, expiry, or store state that require refetch
103
- watch(
104
- () => {
105
- const m = responseMeta.value;
106
- return [
107
- m.expiresAt,
108
- m.expiryStatus,
109
- stateRef.value.lastReset,
110
- argsKey.value,
111
- ];
112
- },
113
- () => {
114
- return maybeFetch();
115
- },
116
- );
89
+ watch(refetchTriggers(responseMeta, stateRef, argsKey), () => {
90
+ // errors are stored and surfaced through the returned ref
91
+ maybeFetch().catch(() => {});
92
+ });
117
93
 
118
- // Maintain GC refcounts on data mount/changes
119
- watch(
120
- () => responseMeta.value.data,
121
- (_newVal, _oldVal, onCleanup) => {
122
- const decrement = responseMeta.value.countRef();
123
- onCleanup(() => decrement?.());
124
- },
125
- { immediate: true },
94
+ // Like React, fully "valid" data never suspends, even when stale: show it and refetch in
95
+ // the background. Only missing or invalid data waits for the fetch.
96
+ const suspend = responseMeta.value.expiryStatus !== ExpiryStatus.Valid;
97
+ const initialFetch = maybeFetch();
98
+ if (suspend) await initialFetch;
99
+ else initialFetch.catch(() => {});
100
+
101
+ // While a fetch for new args (or for a key with no data) is in flight, where React's
102
+ // useSuspense would suspend, keep returning the last resolved data. Vue can't re-suspend
103
+ // after setup, so this avoids yielding `undefined` mid-transition. A key that already
104
+ // has data keeps showing current store data, even while stale or refetching.
105
+ let lastData: unknown;
106
+ let lastKey = '';
107
+ const loading = computed(() => {
108
+ const meta = responseMeta.value;
109
+ const key = argsKey.value;
110
+ return (
111
+ !!key &&
112
+ fetchingKey.value === key &&
113
+ (lastKey !== key || meta.data === undefined) &&
114
+ meta.expiryStatus !== ExpiryStatus.Valid &&
115
+ isStale(meta)
116
+ );
117
+ });
118
+ // surface fetch errors for the current args like React's useSuspense does
119
+ const error = computed(() =>
120
+ loading.value ? undefined : (
121
+ controller.getError(endpoint, ...resolvedArgs.value, stateRef.value)
122
+ ),
126
123
  );
124
+ const data = computed(() => {
125
+ if (loading.value || error.value) return lastData;
126
+ lastKey = argsKey.value;
127
+ return (lastData = responseMeta.value.data);
128
+ });
127
129
 
128
- // Trigger on initial call
129
- await maybeFetch();
130
+ // Throw on every read; a computed that throws would return its cached value on the next read
131
+ const result = customRef(() => ({
132
+ get() {
133
+ if (error.value) throw error.value;
134
+ return data.value;
135
+ },
136
+ set() {},
137
+ }));
130
138
 
131
- // Return readonly computed ref - Vue automatically unwraps in templates and reactive contexts
132
- return readonly(computed(() => responseMeta.value.data));
139
+ // Return readonly ref - Vue automatically unwraps in templates and reactive contexts
140
+ return readonly(result);
133
141
  }