@tanstack/solid-query 6.0.0-rc.4 → 6.0.0-rc.6

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.
@@ -11,25 +11,126 @@ import type {
11
11
  import type { Accessor } from 'solid-js'
12
12
  import type { QueryClient } from './QueryClient'
13
13
 
14
- type MutationStateOptions<TResult = MutationState> = {
14
+ type MutationTypeFromResult<TResult> = [TResult] extends [
15
+ MutationState<
16
+ infer TData,
17
+ infer TError,
18
+ infer TVariables,
19
+ infer TOnMutateResult
20
+ >,
21
+ ]
22
+ ? Mutation<TData, TError, TVariables, TOnMutateResult>
23
+ : Mutation
24
+
25
+ type MutationStateOptions<
26
+ TResult = MutationState,
27
+ TMutation extends Mutation<any, any, any, any> =
28
+ MutationTypeFromResult<TResult>,
29
+ > = {
15
30
  filters?: MutationFilters
16
- select?: (mutation: Mutation) => TResult
31
+ select?: (mutation: TMutation) => TResult
17
32
  }
18
33
 
19
- function getResult<TResult = MutationState>(
34
+ /**
35
+ * Collects the mutations in the cache that match `options.filters`, mapped with `options.select`
36
+ * (or to their state, by default).
37
+ * @param mutationCache - The mutation cache to read.
38
+ * @param options - The `filters` to match and the `select` function to map each mutation with.
39
+ * @returns The selected value of every matching mutation.
40
+ */
41
+ function getResult<
42
+ TResult = MutationState,
43
+ TMutation extends Mutation<any, any, any, any> =
44
+ MutationTypeFromResult<TResult>,
45
+ >(
20
46
  mutationCache: MutationCache,
21
- options: MutationStateOptions<TResult>,
47
+ options: MutationStateOptions<TResult, TMutation>,
22
48
  ): Array<TResult> {
23
49
  return mutationCache
24
50
  .findAll(options.filters)
25
51
  .map(
26
52
  (mutation): TResult =>
27
- (options.select ? options.select(mutation) : mutation.state) as TResult,
53
+ (options.select
54
+ ? options.select(mutation as TMutation)
55
+ : mutation.state) as TResult,
28
56
  )
29
57
  }
30
58
 
31
- export function useMutationState<TResult = MutationState>(
32
- options: Accessor<MutationStateOptions<TResult>> = () => ({}),
59
+ /**
60
+ * `useMutationState` is a primitive that gives you access to all mutations in the `MutationCache`. You can pass
61
+ * `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
62
+ * state.
63
+ * @param options - An accessor returning the `filters` to narrow down matched mutations, and an optional
64
+ * `select` to transform the mutation state.
65
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
66
+ * will be used.
67
+ * @returns An accessor for an array of whatever `select` returns for each matching mutation.
68
+ * @example
69
+ * Get all variables of all running mutations:
70
+ * ```tsx
71
+ * import { useMutationState } from '@tanstack/solid-query'
72
+ *
73
+ * function PendingPosts() {
74
+ * const pendingVariables = useMutationState(() => ({
75
+ * filters: { status: 'pending' },
76
+ * select: (mutation) => mutation.state.variables,
77
+ * }))
78
+ *
79
+ * return <>{pendingVariables().length} posts saving...</>
80
+ * }
81
+ * ```
82
+ * @example
83
+ * Get all data for specific mutations via the `mutationKey`:
84
+ * ```tsx
85
+ * import { useMutation, useMutationState } from '@tanstack/solid-query'
86
+ *
87
+ * const mutationKey = ['posts']
88
+ *
89
+ * function Posts() {
90
+ * // Some mutation that we want to get the state for
91
+ * const createPostsMutation = useMutation(() => ({
92
+ * mutationKey,
93
+ * mutationFn: createPosts,
94
+ * }))
95
+ *
96
+ * const savedPosts = useMutationState(() => ({
97
+ * // this mutation key needs to match the mutation key of the given mutation (see above)
98
+ * filters: { mutationKey, status: 'success' },
99
+ * select: (mutation) => mutation.state.data,
100
+ * }))
101
+ *
102
+ * return (
103
+ * <button onClick={() => createPostsMutation.mutate(['New Post'])}>
104
+ * Create post ({savedPosts().length} saved so far)
105
+ * </button>
106
+ * )
107
+ * }
108
+ * ```
109
+ * @example
110
+ * Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
111
+ * entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
112
+ * last item that `useMutationState` returns to get the latest successful invocation:
113
+ * ```tsx
114
+ * import { useMutationState } from '@tanstack/solid-query'
115
+ *
116
+ * function LatestPost() {
117
+ * const savedPosts = useMutationState(() => ({
118
+ * filters: { mutationKey: ['posts'], status: 'success' },
119
+ * select: (mutation) => mutation.state.data,
120
+ * }))
121
+ *
122
+ * const latestPost = () => savedPosts()[savedPosts().length - 1]
123
+ *
124
+ * return <span>{latestPost()?.title}</span>
125
+ * }
126
+ * ```
127
+ */
128
+ export function useMutationState<
129
+ TResult = MutationState,
130
+ TMutation extends Mutation<any, any, any, any> =
131
+ MutationTypeFromResult<TResult>,
132
+ >(
133
+ options: Accessor<MutationStateOptions<TResult, TMutation>> = () => ({}),
33
134
  queryClient?: Accessor<QueryClient>,
34
135
  ): Accessor<Array<TResult>> {
35
136
  const client = createMemo(() => useQueryClient(queryClient?.()))
package/src/useQueries.ts CHANGED
@@ -169,6 +169,91 @@ type QueriesResults<
169
169
  >
170
170
  : { [K in keyof T]: GetResults<T[K]> }
171
171
 
172
+ /**
173
+ * The `useQueries` primitive can be used to fetch a variable number of queries.
174
+ *
175
+ * The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see
176
+ * `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
177
+ * own top-level second argument, rather than per query.
178
+ *
179
+ * Having the same query key more than once in the array of query objects may cause some data to be shared
180
+ * between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
181
+ * structure.
182
+ *
183
+ * The `combine` option can be used to combine the results of the queries into a single value. The result will
184
+ * be structurally shared to be as referentially stable as possible.
185
+ *
186
+ * `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
187
+ * previously rendered queries, because the number of queries can differ between renders.
188
+ * @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
189
+ * function.
190
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
191
+ * will be used.
192
+ * @returns The combined result. Without `combine`, this is an array with all the query results, in the same
193
+ * order as the input. When `combine` is provided, this is the value returned by `combine` instead.
194
+ * @example
195
+ * ```tsx
196
+ * import { For } from 'solid-js'
197
+ * import { useQueries } from '@tanstack/solid-query'
198
+ *
199
+ * function Posts(props: { ids: Array<number> }) {
200
+ * const postQueries = useQueries(() => ({
201
+ * queries: props.ids.map((id) => ({
202
+ * queryKey: ['post', id],
203
+ * queryFn: () => fetchPost(id),
204
+ * staleTime: Infinity,
205
+ * })),
206
+ * }))
207
+ *
208
+ * return (
209
+ * <ul>
210
+ * <For each={postQueries}>
211
+ * {(postQuery) => {
212
+ * if (postQuery.isPending) return <li>Loading...</li>
213
+ * if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
214
+ * return <li>{postQuery.data.title}</li>
215
+ * }}
216
+ * </For>
217
+ * </ul>
218
+ * )
219
+ * }
220
+ * ```
221
+ * @example
222
+ * Combining results into a single value:
223
+ * ```tsx
224
+ * import { For, Match, Switch } from 'solid-js'
225
+ * import { useQueries } from '@tanstack/solid-query'
226
+ *
227
+ * function Posts(props: { ids: Array<number> }) {
228
+ * const combinedPostsQuery = useQueries(() => ({
229
+ * queries: props.ids.map((id) => ({
230
+ * queryKey: ['post', id],
231
+ * queryFn: () => fetchPost(id),
232
+ * })),
233
+ * combine: (postQueries) => {
234
+ * return {
235
+ * data: postQueries.map((postQuery) => postQuery.data),
236
+ * isPending: postQueries.some((postQuery) => postQuery.isPending),
237
+ * isError: postQueries.some((postQuery) => postQuery.isError),
238
+ * }
239
+ * },
240
+ * }))
241
+ *
242
+ * return (
243
+ * <Switch
244
+ * fallback={
245
+ * <ul>
246
+ * <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
247
+ * </ul>
248
+ * }
249
+ * >
250
+ * <Match when={combinedPostsQuery.isPending}>Loading...</Match>
251
+ * <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
252
+ * </Switch>
253
+ * )
254
+ * }
255
+ * ```
256
+ */
172
257
  export function useQueries<
173
258
  T extends Array<any>,
174
259
  TCombinedResult = QueriesResults<T>,
@@ -235,5 +320,5 @@ export function useQueries<
235
320
  if (descriptor) descriptor.configurable = true
236
321
  return descriptor
237
322
  },
238
- }) as TCombinedResult
323
+ })
239
324
  }
package/src/useQuery.ts CHANGED
@@ -14,25 +14,228 @@ import type {
14
14
  UndefinedInitialDataOptions,
15
15
  } from './queryOptions'
16
16
 
17
+ /**
18
+ * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
19
+ * The query runs when the options call for it — `enabled: false` skips the initial fetch.
20
+ *
21
+ * This overload is selected when `initialData` is known to be defined, so the resulting `data` is typed as never
22
+ * `undefined` (unless a `select` changes `TData` to include `undefined`). At runtime, `data` is still `undefined`
23
+ * if `select` throws on its first call.
24
+ * @param options - An accessor returning the {@link DefinedInitialDataOptions} to use — everything you can
25
+ * pass to `useQuery`, with `initialData` known to be defined.
26
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
27
+ * will be used.
28
+ * @returns The current query result, as a Solid store, typed so that `status` is `success` or `error`
29
+ * (`status` never resolves to `pending` in this overload's type, since `initialData` guarantees data upfront).
30
+ * `status` is `error` if the query has an error from a fetch that failed after its retries or if `select`
31
+ * threw, and `success` otherwise. `isSuccess`/`isError` are derived booleans for convenience.
32
+ * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
33
+ * @example
34
+ * ```tsx
35
+ * import { For } from 'solid-js'
36
+ * import { useQuery } from '@tanstack/solid-query'
37
+ *
38
+ * function Posts() {
39
+ * // `postsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
40
+ * // list stays visible alongside the error.
41
+ * const postsQuery = useQuery(() => ({
42
+ * queryKey: ['posts'],
43
+ * queryFn: fetchPosts,
44
+ * initialData: [],
45
+ * }))
46
+ *
47
+ * return (
48
+ * <div>
49
+ * {postsQuery.isError ? <span>Error: {postsQuery.error.message}</span> : null}
50
+ * <ul>
51
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
52
+ * </ul>
53
+ * </div>
54
+ * )
55
+ * }
56
+ * ```
57
+ */
17
58
  export function useQuery<
18
59
  TQueryFnData = unknown,
19
60
  TError = DefaultError,
20
61
  TData = TQueryFnData,
21
62
  TQueryKey extends QueryKey = QueryKey,
22
63
  >(
23
- options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
64
+ options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
24
65
  queryClient?: () => QueryClient,
25
- ): UseQueryResult<TData, TError>
66
+ ): DefinedUseQueryResult<TData, TError>
26
67
 
68
+ /**
69
+ * Subscribes to a query: a declarative dependency on an asynchronous source of data that is tied to a unique key.
70
+ * The query runs when the options call for it — `enabled: false` skips the initial fetch.
71
+ * @param options - An accessor returning the {@link UndefinedInitialDataOptions} to use — everything you can
72
+ * pass to `useQuery`.
73
+ * @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
74
+ * will be used.
75
+ * @returns The current query result, as a Solid store. `status` is `error` if the query has an error from
76
+ * a fetch that failed after its retries or if `select` threw, `success` if the query has data to display
77
+ * (including `placeholderData`), and `pending` otherwise. `isPending`/`isSuccess`/`isError` are derived
78
+ * booleans for convenience.
79
+ * @see {@link queryOptions} to share these options between `useQuery` and imperative APIs like `queryClient.query`.
80
+ * @example
81
+ * ```tsx
82
+ * import { For, Match, Switch } from 'solid-js'
83
+ * import { useQuery } from '@tanstack/solid-query'
84
+ *
85
+ * function Posts() {
86
+ * const postsQuery = useQuery(() => ({
87
+ * queryKey: ['posts'],
88
+ * queryFn: fetchPosts,
89
+ * }))
90
+ *
91
+ * return (
92
+ * <Switch>
93
+ * <Match when={postsQuery.isPending}>Loading...</Match>
94
+ * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
95
+ * <Match when={postsQuery.isSuccess}>
96
+ * <ul>
97
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
98
+ * </ul>
99
+ * <div>{postsQuery.isFetching ? 'Background Updating...' : ' '}</div>
100
+ * </Match>
101
+ * </Switch>
102
+ * )
103
+ * }
104
+ * ```
105
+ * @example
106
+ * `select` derives whatever `data` a component needs from the cached value, without changing what's
107
+ * actually stored in the cache — the cache still holds the full `Post[]`, but `data` here is a `number`:
108
+ * ```tsx
109
+ * import { Match, Switch } from 'solid-js'
110
+ * import { useQuery } from '@tanstack/solid-query'
111
+ *
112
+ * function PostCount() {
113
+ * const postsQuery = useQuery(() => ({
114
+ * queryKey: ['posts'],
115
+ * queryFn: fetchPosts,
116
+ * select: (posts) => posts.length,
117
+ * }))
118
+ *
119
+ * return (
120
+ * <Switch>
121
+ * <Match when={postsQuery.isPending}>Loading...</Match>
122
+ * <Match when={postsQuery.isError}>Error: {postsQuery.error.message}</Match>
123
+ * <Match when={postsQuery.isSuccess}>{postsQuery.data} posts</Match>
124
+ * </Switch>
125
+ * )
126
+ * }
127
+ * ```
128
+ * @example
129
+ * A dependent query, only enabled once `postId` is set:
130
+ * ```tsx
131
+ * import { Match, Switch } from 'solid-js'
132
+ * import { useQuery } from '@tanstack/solid-query'
133
+ *
134
+ * function Post(props: { postId: number | undefined }) {
135
+ * const postQuery = useQuery(() => ({
136
+ * queryKey: ['post', props.postId],
137
+ * queryFn: () => fetchPost(props.postId!),
138
+ * enabled: props.postId != null,
139
+ * }))
140
+ *
141
+ * return (
142
+ * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
143
+ * <Match when={props.postId == null}>Select a post</Match>
144
+ * <Match when={postQuery.isLoading}>Loading...</Match>
145
+ * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
146
+ * </Switch>
147
+ * )
148
+ * }
149
+ * ```
150
+ * @example
151
+ * The same dependent query, using `skipToken` to disable it in a type-safe way instead of relying on
152
+ * `enabled`. The non-null assertion is still needed — Solid's `props` narrowing doesn't survive into the
153
+ * `queryFn` closure the way a local `const` would — but `skipToken` keeps `queryFn`'s return type accurate
154
+ * without it. `refetch` doesn't work while `queryFn` is `skipToken` — use `enabled: false` instead if you
155
+ * need to trigger the query manually:
156
+ * ```tsx
157
+ * import { Match, Switch } from 'solid-js'
158
+ * import { skipToken, useQuery } from '@tanstack/solid-query'
159
+ *
160
+ * function Post(props: { postId: number | undefined }) {
161
+ * const postQuery = useQuery(() => ({
162
+ * queryKey: ['post', props.postId],
163
+ * queryFn: props.postId != null ? () => fetchPost(props.postId!) : skipToken,
164
+ * }))
165
+ *
166
+ * return (
167
+ * <Switch fallback={<h1>{postQuery.data?.title}</h1>}>
168
+ * <Match when={props.postId == null}>Select a post</Match>
169
+ * <Match when={postQuery.isLoading}>Loading...</Match>
170
+ * <Match when={postQuery.isError}>Error: {postQuery.error.message}</Match>
171
+ * </Switch>
172
+ * )
173
+ * }
174
+ * ```
175
+ * @example
176
+ * Seeding a detail query from an already-cached list, to skip the loading state. `initialDataUpdatedAt` carries
177
+ * over the list's own fetch time, so that if you set a `staleTime`, it's measured from when the list was
178
+ * fetched rather than from now:
179
+ * ```tsx
180
+ * import { useQuery, useQueryClient } from '@tanstack/solid-query'
181
+ *
182
+ * function Post(props: { postId: number }) {
183
+ * const queryClient = useQueryClient()
184
+ *
185
+ * const postQuery = useQuery(() => ({
186
+ * queryKey: ['post', props.postId],
187
+ * queryFn: () => fetchPost(props.postId),
188
+ * initialData: () =>
189
+ * queryClient
190
+ * .getQueryData<Array<Post>>(['posts'])
191
+ * ?.find((post) => post.id === props.postId),
192
+ * initialDataUpdatedAt: () =>
193
+ * queryClient.getQueryState(['posts'])?.dataUpdatedAt,
194
+ * }))
195
+ *
196
+ * return postQuery.isError ? <span>Error: {postQuery.error.message}</span> : <h1>{postQuery.data?.title}</h1>
197
+ * }
198
+ * ```
199
+ * @example
200
+ * Paginated data, keeping the previous page's data visible while the next page loads:
201
+ * ```tsx
202
+ * import { For, createSignal } from 'solid-js'
203
+ * import { keepPreviousData, useQuery } from '@tanstack/solid-query'
204
+ *
205
+ * function Posts() {
206
+ * const [page, setPage] = createSignal(0)
207
+ *
208
+ * const postsQuery = useQuery(() => ({
209
+ * queryKey: ['posts', page()],
210
+ * queryFn: () => fetchPosts(page()),
211
+ * placeholderData: keepPreviousData,
212
+ * }))
213
+ *
214
+ * return (
215
+ * <div>
216
+ * <ul>
217
+ * <For each={postsQuery.data}>{(post) => <li>{post.title}</li>}</For>
218
+ * </ul>
219
+ * <button
220
+ * disabled={postsQuery.isPlaceholderData}
221
+ * onClick={() => setPage((old) => old + 1)}
222
+ * >
223
+ * Next Page
224
+ * </button>
225
+ * </div>
226
+ * )
227
+ * }
228
+ * ```
229
+ */
27
230
  export function useQuery<
28
231
  TQueryFnData = unknown,
29
232
  TError = DefaultError,
30
233
  TData = TQueryFnData,
31
234
  TQueryKey extends QueryKey = QueryKey,
32
235
  >(
33
- options: DefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
236
+ options: UndefinedInitialDataOptions<TQueryFnData, TError, TData, TQueryKey>,
34
237
  queryClient?: () => QueryClient,
35
- ): DefinedUseQueryResult<TData, TError>
238
+ ): UseQueryResult<TData, TError>
36
239
  export function useQuery<
37
240
  TQueryFnData,
38
241
  TError = DefaultError,