@tanstack/solid-query 5.102.8 → 5.103.1
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.
- package/build/dev.cjs +407 -0
- package/build/dev.js +407 -0
- package/build/index.d.cts +1194 -1
- package/build/index.d.cts.map +1 -1
- package/build/index.d.ts +1194 -1
- package/build/index.d.ts.map +1 -1
- package/build/index.js.map +1 -1
- package/package.json +10 -10
- package/src/QueryClient.ts +33 -0
- package/src/QueryClientProvider.tsx +41 -0
- package/src/infiniteQueryOptions.ts +111 -0
- package/src/isRestoring.ts +12 -0
- package/src/mutationOptions.ts +55 -0
- package/src/queryOptions.ts +98 -4
- package/src/types.ts +139 -0
- package/src/useInfiniteQuery.ts +151 -0
- package/src/useIsFetching.ts +22 -0
- package/src/useIsMutating.ts +21 -0
- package/src/useMutation.ts +159 -1
- package/src/useMutationState.ts +73 -0
- package/src/useQueries.ts +87 -0
- package/src/useQuery.ts +199 -0
package/src/useInfiniteQuery.ts
CHANGED
|
@@ -19,6 +19,54 @@ import type {
|
|
|
19
19
|
UndefinedInitialDataInfiniteOptions,
|
|
20
20
|
} from './infiniteQueryOptions'
|
|
21
21
|
|
|
22
|
+
/**
|
|
23
|
+
* The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
|
|
24
|
+
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
|
|
25
|
+
*
|
|
26
|
+
* This overload is selected when `initialData` is set.
|
|
27
|
+
*
|
|
28
|
+
* @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
|
|
29
|
+
* refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
|
|
30
|
+
* actions, or add conditions like `hasNextPage && !isFetching`.
|
|
31
|
+
* @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
|
|
32
|
+
* @param options - An accessor returning the {@link DefinedInitialDataInfiniteOptions} to use — everything you
|
|
33
|
+
* can pass to `useInfiniteQuery`, with `initialData` set.
|
|
34
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
35
|
+
* will be used.
|
|
36
|
+
* @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
|
|
37
|
+
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
|
|
38
|
+
* `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
|
|
39
|
+
* `InfiniteData<TQueryFnData>` shape.
|
|
40
|
+
*
|
|
41
|
+
* @example
|
|
42
|
+
* ```tsx
|
|
43
|
+
* import { For } from 'solid-js'
|
|
44
|
+
* import { useInfiniteQuery } from '@tanstack/solid-query'
|
|
45
|
+
*
|
|
46
|
+
* function Projects() {
|
|
47
|
+
* // `projectsQuery.data` is never `undefined`, thanks to `initialData` — even if a refetch fails, so the
|
|
48
|
+
* // list stays visible alongside the error.
|
|
49
|
+
* const projectsQuery = useInfiniteQuery(() => ({
|
|
50
|
+
* queryKey: ['projects'],
|
|
51
|
+
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
|
52
|
+
* initialPageParam: 0,
|
|
53
|
+
* getNextPageParam: (lastPage) => lastPage.nextId,
|
|
54
|
+
* initialData: { pages: [], pageParams: [] },
|
|
55
|
+
* }))
|
|
56
|
+
*
|
|
57
|
+
* return (
|
|
58
|
+
* <div>
|
|
59
|
+
* {projectsQuery.isError ? <span>Error: {projectsQuery.error.message}</span> : null}
|
|
60
|
+
* <ul>
|
|
61
|
+
* <For each={projectsQuery.data.pages}>
|
|
62
|
+
* {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
|
|
63
|
+
* </For>
|
|
64
|
+
* </ul>
|
|
65
|
+
* </div>
|
|
66
|
+
* )
|
|
67
|
+
* }
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
22
70
|
export function useInfiniteQuery<
|
|
23
71
|
TQueryFnData,
|
|
24
72
|
TError = DefaultError,
|
|
@@ -35,6 +83,109 @@ export function useInfiniteQuery<
|
|
|
35
83
|
>,
|
|
36
84
|
queryClient?: Accessor<QueryClient>,
|
|
37
85
|
): DefinedUseInfiniteQueryResult<TData, TError>
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The options for `useInfiniteQuery` are identical to `useQuery`, with the addition of
|
|
89
|
+
* `initialPageParam`, `getNextPageParam`, `getPreviousPageParam`, and `maxPages`.
|
|
90
|
+
*
|
|
91
|
+
* @remarks Keep in mind that imperative fetch calls, such as `fetchNextPage`, may interfere with the default
|
|
92
|
+
* refetch behavior, resulting in outdated data. Make sure to call these functions only in response to user
|
|
93
|
+
* actions, or add conditions like `hasNextPage && !isFetching`.
|
|
94
|
+
* @see {@link infiniteQueryOptions} to share these options between `useInfiniteQuery` and imperative APIs like `queryClient.infiniteQuery`.
|
|
95
|
+
* @param options - An accessor returning the {@link UndefinedInitialDataInfiniteOptions} to use — everything
|
|
96
|
+
* you can pass to `useInfiniteQuery`.
|
|
97
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
98
|
+
* will be used.
|
|
99
|
+
* @returns The same properties as `useQuery`, with the addition of `fetchNextPage`, `fetchPreviousPage`,
|
|
100
|
+
* `hasNextPage`, `hasPreviousPage`, `isFetchingNextPage`, and `isFetchingPreviousPage`. `data.pages` and
|
|
101
|
+
* `data.pageParams` are also added, as long as a `select` doesn't change `TData` away from its default
|
|
102
|
+
* `InfiniteData<TQueryFnData>` shape.
|
|
103
|
+
*
|
|
104
|
+
* @example
|
|
105
|
+
* Fetching the next page from a "Load More" button click:
|
|
106
|
+
* ```tsx
|
|
107
|
+
* import { For, Match, Switch } from 'solid-js'
|
|
108
|
+
* import { useInfiniteQuery } from '@tanstack/solid-query'
|
|
109
|
+
*
|
|
110
|
+
* function Projects() {
|
|
111
|
+
* const projectsQuery = useInfiniteQuery(() => ({
|
|
112
|
+
* queryKey: ['projects'],
|
|
113
|
+
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
|
114
|
+
* initialPageParam: 0,
|
|
115
|
+
* getNextPageParam: (lastPage) => lastPage.nextId,
|
|
116
|
+
* }))
|
|
117
|
+
*
|
|
118
|
+
* return (
|
|
119
|
+
* <Switch>
|
|
120
|
+
* <Match when={projectsQuery.isPending}>Loading...</Match>
|
|
121
|
+
* <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
|
|
122
|
+
* <Match when={projectsQuery.isSuccess}>
|
|
123
|
+
* <ul>
|
|
124
|
+
* <For each={projectsQuery.data.pages}>
|
|
125
|
+
* {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
|
|
126
|
+
* </For>
|
|
127
|
+
* </ul>
|
|
128
|
+
* <button
|
|
129
|
+
* onClick={() => projectsQuery.fetchNextPage()}
|
|
130
|
+
* disabled={!projectsQuery.hasNextPage || projectsQuery.isFetching}
|
|
131
|
+
* >
|
|
132
|
+
* {projectsQuery.isFetchingNextPage
|
|
133
|
+
* ? 'Loading more...'
|
|
134
|
+
* : projectsQuery.hasNextPage
|
|
135
|
+
* ? 'Load More'
|
|
136
|
+
* : 'Nothing more to load'}
|
|
137
|
+
* </button>
|
|
138
|
+
* </Match>
|
|
139
|
+
* </Switch>
|
|
140
|
+
* )
|
|
141
|
+
* }
|
|
142
|
+
* ```
|
|
143
|
+
*
|
|
144
|
+
* @example
|
|
145
|
+
* Fetching the next page automatically as the user scrolls, using an `IntersectionObserver` on a
|
|
146
|
+
* sentinel element after the list:
|
|
147
|
+
* ```tsx
|
|
148
|
+
* import { For, Match, Switch, createEffect, onCleanup } from 'solid-js'
|
|
149
|
+
* import { useInfiniteQuery } from '@tanstack/solid-query'
|
|
150
|
+
*
|
|
151
|
+
* function Projects() {
|
|
152
|
+
* const projectsQuery = useInfiniteQuery(() => ({
|
|
153
|
+
* queryKey: ['projects'],
|
|
154
|
+
* queryFn: ({ pageParam }) => fetchProjects(pageParam),
|
|
155
|
+
* initialPageParam: 0,
|
|
156
|
+
* getNextPageParam: (lastPage) => lastPage.nextId,
|
|
157
|
+
* }))
|
|
158
|
+
*
|
|
159
|
+
* let sentinelRef: HTMLDivElement | undefined
|
|
160
|
+
*
|
|
161
|
+
* createEffect(() => {
|
|
162
|
+
* if (sentinelRef == null || !projectsQuery.hasNextPage || projectsQuery.isFetching) return
|
|
163
|
+
*
|
|
164
|
+
* const observer = new IntersectionObserver(([entry]) => {
|
|
165
|
+
* if (entry?.isIntersecting) projectsQuery.fetchNextPage()
|
|
166
|
+
* })
|
|
167
|
+
* observer.observe(sentinelRef)
|
|
168
|
+
*
|
|
169
|
+
* onCleanup(() => observer.disconnect())
|
|
170
|
+
* })
|
|
171
|
+
*
|
|
172
|
+
* return (
|
|
173
|
+
* <Switch>
|
|
174
|
+
* <Match when={projectsQuery.isPending}>Loading...</Match>
|
|
175
|
+
* <Match when={projectsQuery.isError}>Error: {projectsQuery.error.message}</Match>
|
|
176
|
+
* <Match when={projectsQuery.isSuccess}>
|
|
177
|
+
* <ul>
|
|
178
|
+
* <For each={projectsQuery.data.pages}>
|
|
179
|
+
* {(page) => <For each={page.projects}>{(p) => <li>{p.name}</li>}</For>}
|
|
180
|
+
* </For>
|
|
181
|
+
* </ul>
|
|
182
|
+
* <div ref={sentinelRef}>{projectsQuery.isFetchingNextPage ? 'Loading more...' : null}</div>
|
|
183
|
+
* </Match>
|
|
184
|
+
* </Switch>
|
|
185
|
+
* )
|
|
186
|
+
* }
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
38
189
|
export function useInfiniteQuery<
|
|
39
190
|
TQueryFnData,
|
|
40
191
|
TError = DefaultError,
|
package/src/useIsFetching.ts
CHANGED
|
@@ -4,6 +4,28 @@ import type { QueryFilters } from '@tanstack/query-core'
|
|
|
4
4
|
import type { QueryClient } from './QueryClient'
|
|
5
5
|
import type { Accessor } from 'solid-js'
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* The `useIsFetching` hook returns the `number` of the queries that your application is loading or fetching
|
|
9
|
+
* in the background (useful for app-wide loading indicators).
|
|
10
|
+
*
|
|
11
|
+
* @param filters - An accessor returning the {@link QueryFilters} to narrow down the matched queries.
|
|
12
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
13
|
+
* will be used.
|
|
14
|
+
* @returns An accessor for the `number` of the queries that your application is currently loading or fetching
|
|
15
|
+
* in the background.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```tsx
|
|
19
|
+
* import { useIsFetching } from '@tanstack/solid-query'
|
|
20
|
+
*
|
|
21
|
+
* function GlobalLoadingIndicator() {
|
|
22
|
+
* // How many queries matching the posts prefix are fetching?
|
|
23
|
+
* const isFetchingPosts = useIsFetching(() => ({ queryKey: ['posts'] }))
|
|
24
|
+
*
|
|
25
|
+
* return isFetchingPosts() > 0 ? <span>Loading posts...</span> : null
|
|
26
|
+
* }
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
7
29
|
export function useIsFetching(
|
|
8
30
|
filters?: Accessor<QueryFilters>,
|
|
9
31
|
queryClient?: Accessor<QueryClient>,
|
package/src/useIsMutating.ts
CHANGED
|
@@ -4,6 +4,27 @@ import type { MutationFilters } from '@tanstack/query-core'
|
|
|
4
4
|
import type { QueryClient } from './QueryClient'
|
|
5
5
|
import type { Accessor } from 'solid-js'
|
|
6
6
|
|
|
7
|
+
/**
|
|
8
|
+
* The `useIsMutating` hook returns the `number` of mutations that your application currently has `pending`
|
|
9
|
+
* (useful for app-wide loading indicators).
|
|
10
|
+
*
|
|
11
|
+
* @param filters - An accessor returning the {@link MutationFilters} to narrow down the matched mutations.
|
|
12
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
13
|
+
* will be used.
|
|
14
|
+
* @returns An accessor for the `number` of the mutations that your application currently has `pending`.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```tsx
|
|
18
|
+
* import { useIsMutating } from '@tanstack/solid-query'
|
|
19
|
+
*
|
|
20
|
+
* function PostsMutatingIndicator() {
|
|
21
|
+
* // How many mutations matching the posts prefix are in progress?
|
|
22
|
+
* const isMutatingPosts = useIsMutating(() => ({ mutationKey: ['posts'] }))
|
|
23
|
+
*
|
|
24
|
+
* return isMutatingPosts() > 0 ? <span>Saving posts...</span> : null
|
|
25
|
+
* }
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
7
28
|
export function useIsMutating(
|
|
8
29
|
filters?: Accessor<MutationFilters>,
|
|
9
30
|
queryClient?: Accessor<QueryClient>,
|
package/src/useMutation.ts
CHANGED
|
@@ -11,7 +11,165 @@ import type {
|
|
|
11
11
|
} from './types'
|
|
12
12
|
import type { Accessor } from 'solid-js'
|
|
13
13
|
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* @param options - An accessor returning the {@link UseMutationOptions} to use.
|
|
16
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
17
|
+
* will be used.
|
|
18
|
+
* @returns `mutate`/`mutateAsync` also accept per-call `onSuccess`/`onError`/`onSettled` callbacks as a second
|
|
19
|
+
* argument, useful for triggering call-site side effects (e.g. navigation) without coupling them to the shared
|
|
20
|
+
* mutation definition. Hook-level callbacks (passed to `options`) fire for every mutation; per-call callbacks
|
|
21
|
+
* fire only for the latest call you've made, and only while the component is still mounted — unmounting before
|
|
22
|
+
* the mutation settles removes the subscription and prevents them from firing.
|
|
23
|
+
*
|
|
24
|
+
* @example
|
|
25
|
+
* ```tsx
|
|
26
|
+
* import { useMutation, useQueryClient } from '@tanstack/solid-query'
|
|
27
|
+
*
|
|
28
|
+
* function TodoItem(props: { id: number }) {
|
|
29
|
+
* const queryClient = useQueryClient()
|
|
30
|
+
*
|
|
31
|
+
* const deleteTodoMutation = useMutation(() => ({
|
|
32
|
+
* mutationFn: deleteTodo,
|
|
33
|
+
* onSuccess: () => {
|
|
34
|
+
* queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
35
|
+
* },
|
|
36
|
+
* }))
|
|
37
|
+
*
|
|
38
|
+
* return (
|
|
39
|
+
* <button onClick={() => deleteTodoMutation.mutate({ id: props.id })} disabled={deleteTodoMutation.isPending}>
|
|
40
|
+
* Delete
|
|
41
|
+
* </button>
|
|
42
|
+
* )
|
|
43
|
+
* }
|
|
44
|
+
* ```
|
|
45
|
+
*
|
|
46
|
+
* @example
|
|
47
|
+
* Rendering the mutation's own state, rather than just firing it off:
|
|
48
|
+
* ```tsx
|
|
49
|
+
* import { Match, Switch } from 'solid-js'
|
|
50
|
+
* import { useMutation, useQueryClient } from '@tanstack/solid-query'
|
|
51
|
+
*
|
|
52
|
+
* function AddTodo() {
|
|
53
|
+
* const queryClient = useQueryClient()
|
|
54
|
+
*
|
|
55
|
+
* const addMutation = useMutation(() => ({
|
|
56
|
+
* mutationFn: addTodo,
|
|
57
|
+
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
58
|
+
* }))
|
|
59
|
+
*
|
|
60
|
+
* return (
|
|
61
|
+
* <Switch fallback={<button onClick={() => addMutation.mutate('Item')}>Add</button>}>
|
|
62
|
+
* <Match when={addMutation.isPending}>Adding todo...</Match>
|
|
63
|
+
* <Match when={addMutation.isError}>
|
|
64
|
+
* <div>An error occurred: {addMutation.error?.message}</div>
|
|
65
|
+
* <button onClick={() => addMutation.mutate('Item')}>Add</button>
|
|
66
|
+
* </Match>
|
|
67
|
+
* </Switch>
|
|
68
|
+
* )
|
|
69
|
+
* }
|
|
70
|
+
* ```
|
|
71
|
+
*
|
|
72
|
+
* @example
|
|
73
|
+
* Optimistic update via `onMutate`, rolling back on `onError`:
|
|
74
|
+
* ```tsx
|
|
75
|
+
* import { useMutation, useQueryClient } from '@tanstack/solid-query'
|
|
76
|
+
*
|
|
77
|
+
* function AddTodo() {
|
|
78
|
+
* const queryClient = useQueryClient()
|
|
79
|
+
*
|
|
80
|
+
* const addMutation = useMutation(() => ({
|
|
81
|
+
* mutationFn: addTodo,
|
|
82
|
+
* onMutate: async (newTodo) => {
|
|
83
|
+
* await queryClient.cancelQueries({ queryKey: ['todos'] })
|
|
84
|
+
* const previousTodos = queryClient.getQueryData<Array<string>>(['todos'])
|
|
85
|
+
*
|
|
86
|
+
* queryClient.setQueryData<Array<string>>(['todos'], (old) => [
|
|
87
|
+
* ...(old ?? []),
|
|
88
|
+
* newTodo,
|
|
89
|
+
* ])
|
|
90
|
+
*
|
|
91
|
+
* // Passed to `onError` as `onMutateResult` if the mutation fails.
|
|
92
|
+
* return { previousTodos }
|
|
93
|
+
* },
|
|
94
|
+
* onError: (_err, _newTodo, onMutateResult) => {
|
|
95
|
+
* queryClient.setQueryData(['todos'], onMutateResult?.previousTodos)
|
|
96
|
+
* },
|
|
97
|
+
* onSettled: () => {
|
|
98
|
+
* queryClient.invalidateQueries({ queryKey: ['todos'] })
|
|
99
|
+
* },
|
|
100
|
+
* }))
|
|
101
|
+
*
|
|
102
|
+
* return (
|
|
103
|
+
* <button onClick={() => addMutation.mutate('Item')}>Add</button>
|
|
104
|
+
* )
|
|
105
|
+
* }
|
|
106
|
+
* ```
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* Callbacks passed per call to `mutate` only fire for the last call — `mutateAsync` gives you a
|
|
110
|
+
* promise per call instead, so you can wait for all of them when they succeed:
|
|
111
|
+
* ```tsx
|
|
112
|
+
* import { useMutation, useQueryClient } from '@tanstack/solid-query'
|
|
113
|
+
*
|
|
114
|
+
* function AddTodos() {
|
|
115
|
+
* const queryClient = useQueryClient()
|
|
116
|
+
*
|
|
117
|
+
* const addMutation = useMutation(() => ({
|
|
118
|
+
* mutationFn: addTodo,
|
|
119
|
+
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
120
|
+
* }))
|
|
121
|
+
*
|
|
122
|
+
* async function handleAddAll(todos: Array<string>) {
|
|
123
|
+
* try {
|
|
124
|
+
* await Promise.all(todos.map((todo) => addMutation.mutateAsync(todo)))
|
|
125
|
+
* } catch (error) {
|
|
126
|
+
* console.error('Failed to add todos:', error)
|
|
127
|
+
* }
|
|
128
|
+
* }
|
|
129
|
+
*
|
|
130
|
+
* return (
|
|
131
|
+
* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
|
|
132
|
+
* Add all
|
|
133
|
+
* </button>
|
|
134
|
+
* )
|
|
135
|
+
* }
|
|
136
|
+
* ```
|
|
137
|
+
*
|
|
138
|
+
* @example
|
|
139
|
+
* If some of the mutations above can fail independently of the others, and you want to know which ones
|
|
140
|
+
* did — rather than losing that information the moment the first one rejects — swap `Promise.all` for
|
|
141
|
+
* `Promise.allSettled`:
|
|
142
|
+
* ```tsx
|
|
143
|
+
* import { useMutation, useQueryClient } from '@tanstack/solid-query'
|
|
144
|
+
*
|
|
145
|
+
* function AddTodos() {
|
|
146
|
+
* const queryClient = useQueryClient()
|
|
147
|
+
*
|
|
148
|
+
* const addMutation = useMutation(() => ({
|
|
149
|
+
* mutationFn: addTodo,
|
|
150
|
+
* onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
|
|
151
|
+
* }))
|
|
152
|
+
*
|
|
153
|
+
* async function handleAddAll(todos: Array<string>) {
|
|
154
|
+
* const addResults = await Promise.allSettled(
|
|
155
|
+
* todos.map((todo) => addMutation.mutateAsync(todo)),
|
|
156
|
+
* )
|
|
157
|
+
*
|
|
158
|
+
* addResults.forEach((addResult, index) => {
|
|
159
|
+
* if (addResult.status === 'rejected') {
|
|
160
|
+
* console.error(`Failed to add "${todos[index]}":`, addResult.reason)
|
|
161
|
+
* }
|
|
162
|
+
* })
|
|
163
|
+
* }
|
|
164
|
+
*
|
|
165
|
+
* return (
|
|
166
|
+
* <button onClick={() => handleAddAll(['Todo 1', 'Todo 2', 'Todo 3'])}>
|
|
167
|
+
* Add all
|
|
168
|
+
* </button>
|
|
169
|
+
* )
|
|
170
|
+
* }
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
15
173
|
export function useMutation<
|
|
16
174
|
TData = unknown,
|
|
17
175
|
TError = DefaultError,
|
package/src/useMutationState.ts
CHANGED
|
@@ -48,6 +48,79 @@ function getResult<
|
|
|
48
48
|
)
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* `useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass
|
|
53
|
+
* `filters` ({@link MutationFilters}) to narrow down your mutations, and `select` to transform the mutation
|
|
54
|
+
* state.
|
|
55
|
+
*
|
|
56
|
+
* @param options - An accessor returning the `filters` to narrow down matched mutations, and an optional
|
|
57
|
+
* `select` to transform the mutation state.
|
|
58
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
59
|
+
* will be used.
|
|
60
|
+
* @returns An accessor for an array of whatever `select` returns for each matching mutation.
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* Get all variables of all running mutations:
|
|
64
|
+
* ```tsx
|
|
65
|
+
* import { useMutationState } from '@tanstack/solid-query'
|
|
66
|
+
*
|
|
67
|
+
* function PendingPosts() {
|
|
68
|
+
* const pendingVariables = useMutationState(() => ({
|
|
69
|
+
* filters: { status: 'pending' },
|
|
70
|
+
* select: (mutation) => mutation.state.variables,
|
|
71
|
+
* }))
|
|
72
|
+
*
|
|
73
|
+
* return <>{pendingVariables().length} posts saving...</>
|
|
74
|
+
* }
|
|
75
|
+
* ```
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* Get all data for specific mutations via the `mutationKey`:
|
|
79
|
+
* ```tsx
|
|
80
|
+
* import { useMutation, useMutationState } from '@tanstack/solid-query'
|
|
81
|
+
*
|
|
82
|
+
* const mutationKey = ['posts']
|
|
83
|
+
*
|
|
84
|
+
* function Posts() {
|
|
85
|
+
* // Some mutation that we want to get the state for
|
|
86
|
+
* const createPostsMutation = useMutation(() => ({
|
|
87
|
+
* mutationKey,
|
|
88
|
+
* mutationFn: createPosts,
|
|
89
|
+
* }))
|
|
90
|
+
*
|
|
91
|
+
* const savedPosts = useMutationState(() => ({
|
|
92
|
+
* // this mutation key needs to match the mutation key of the given mutation (see above)
|
|
93
|
+
* filters: { mutationKey, status: 'success' },
|
|
94
|
+
* select: (mutation) => mutation.state.data,
|
|
95
|
+
* }))
|
|
96
|
+
*
|
|
97
|
+
* return (
|
|
98
|
+
* <button onClick={() => createPostsMutation.mutate(['New Post'])}>
|
|
99
|
+
* Create post ({savedPosts().length} saved so far)
|
|
100
|
+
* </button>
|
|
101
|
+
* )
|
|
102
|
+
* }
|
|
103
|
+
* ```
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* Access the latest successful mutation data via the `mutationKey`. Each invocation of `mutate` adds a new
|
|
107
|
+
* entry to the mutation cache for `gcTime` milliseconds — with the `status: 'success'` filter below, check the
|
|
108
|
+
* last item that `useMutationState` returns to get the latest successful invocation:
|
|
109
|
+
* ```tsx
|
|
110
|
+
* import { useMutationState } from '@tanstack/solid-query'
|
|
111
|
+
*
|
|
112
|
+
* function LatestPost() {
|
|
113
|
+
* const savedPosts = useMutationState(() => ({
|
|
114
|
+
* filters: { mutationKey: ['posts'], status: 'success' },
|
|
115
|
+
* select: (mutation) => mutation.state.data,
|
|
116
|
+
* }))
|
|
117
|
+
*
|
|
118
|
+
* const latestPost = () => savedPosts()[savedPosts().length - 1]
|
|
119
|
+
*
|
|
120
|
+
* return <span>{latestPost()?.title}</span>
|
|
121
|
+
* }
|
|
122
|
+
* ```
|
|
123
|
+
*/
|
|
51
124
|
export function useMutationState<
|
|
52
125
|
TResult = MutationState,
|
|
53
126
|
TMutation extends Mutation<any, any, any, any> =
|
package/src/useQueries.ts
CHANGED
|
@@ -184,6 +184,93 @@ type QueriesResults<
|
|
|
184
184
|
>
|
|
185
185
|
: { [K in keyof T]: GetResults<T[K]> }
|
|
186
186
|
|
|
187
|
+
/**
|
|
188
|
+
* The `useQueries` hook can be used to fetch a variable number of queries.
|
|
189
|
+
*
|
|
190
|
+
* The `queries` key accepts an array with query option objects mostly identical to `useQuery` — see
|
|
191
|
+
* `placeholderData` below for the one difference. A custom `QueryClient` is supplied once, as `useQueries`'
|
|
192
|
+
* own top-level second argument, rather than per query.
|
|
193
|
+
*
|
|
194
|
+
* Having the same query key more than once in the array of query objects may cause some data to be shared
|
|
195
|
+
* between queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
|
|
196
|
+
* structure.
|
|
197
|
+
*
|
|
198
|
+
* The `combine` option can be used to combine the results of the queries into a single value. The result will
|
|
199
|
+
* be structurally shared to be as referentially stable as possible.
|
|
200
|
+
*
|
|
201
|
+
* `placeholderData` is supported here too, but unlike `useQuery`, it doesn't receive information from
|
|
202
|
+
* previously rendered queries, because the number of queries can differ between renders.
|
|
203
|
+
* @param queriesOptions - An accessor returning the `queries` array to run, and an optional `combine`
|
|
204
|
+
* function.
|
|
205
|
+
* @param queryClient - An accessor for a custom `QueryClient`. Otherwise, the one from the nearest context
|
|
206
|
+
* will be used.
|
|
207
|
+
* @returns The combined result. Without `combine`, this is an array with all the query results, in the same
|
|
208
|
+
* order as the input. When `combine` is provided, this is the value returned by `combine` instead.
|
|
209
|
+
*
|
|
210
|
+
* @example
|
|
211
|
+
* ```tsx
|
|
212
|
+
* import { For } from 'solid-js'
|
|
213
|
+
* import { useQueries } from '@tanstack/solid-query'
|
|
214
|
+
*
|
|
215
|
+
* function Posts(props: { ids: Array<number> }) {
|
|
216
|
+
* const postQueries = useQueries(() => ({
|
|
217
|
+
* queries: props.ids.map((id) => ({
|
|
218
|
+
* queryKey: ['post', id],
|
|
219
|
+
* queryFn: () => fetchPost(id),
|
|
220
|
+
* staleTime: Infinity,
|
|
221
|
+
* })),
|
|
222
|
+
* }))
|
|
223
|
+
*
|
|
224
|
+
* return (
|
|
225
|
+
* <ul>
|
|
226
|
+
* <For each={postQueries}>
|
|
227
|
+
* {(postQuery) => {
|
|
228
|
+
* if (postQuery.isPending) return <li>Loading...</li>
|
|
229
|
+
* if (postQuery.isError) return <li>Error: {postQuery.error.message}</li>
|
|
230
|
+
* return <li>{postQuery.data.title}</li>
|
|
231
|
+
* }}
|
|
232
|
+
* </For>
|
|
233
|
+
* </ul>
|
|
234
|
+
* )
|
|
235
|
+
* }
|
|
236
|
+
* ```
|
|
237
|
+
*
|
|
238
|
+
* @example
|
|
239
|
+
* Combining results into a single value:
|
|
240
|
+
* ```tsx
|
|
241
|
+
* import { For, Match, Switch } from 'solid-js'
|
|
242
|
+
* import { useQueries } from '@tanstack/solid-query'
|
|
243
|
+
*
|
|
244
|
+
* function Posts(props: { ids: Array<number> }) {
|
|
245
|
+
* const combinedPostsQuery = useQueries(() => ({
|
|
246
|
+
* queries: props.ids.map((id) => ({
|
|
247
|
+
* queryKey: ['post', id],
|
|
248
|
+
* queryFn: () => fetchPost(id),
|
|
249
|
+
* })),
|
|
250
|
+
* combine: (postQueries) => {
|
|
251
|
+
* return {
|
|
252
|
+
* data: postQueries.map((postQuery) => postQuery.data),
|
|
253
|
+
* isPending: postQueries.some((postQuery) => postQuery.isPending),
|
|
254
|
+
* isError: postQueries.some((postQuery) => postQuery.isError),
|
|
255
|
+
* }
|
|
256
|
+
* },
|
|
257
|
+
* }))
|
|
258
|
+
*
|
|
259
|
+
* return (
|
|
260
|
+
* <Switch
|
|
261
|
+
* fallback={
|
|
262
|
+
* <ul>
|
|
263
|
+
* <For each={combinedPostsQuery.data}>{(post) => <li>{post?.title}</li>}</For>
|
|
264
|
+
* </ul>
|
|
265
|
+
* }
|
|
266
|
+
* >
|
|
267
|
+
* <Match when={combinedPostsQuery.isPending}>Loading...</Match>
|
|
268
|
+
* <Match when={combinedPostsQuery.isError}>Error loading posts</Match>
|
|
269
|
+
* </Switch>
|
|
270
|
+
* )
|
|
271
|
+
* }
|
|
272
|
+
* ```
|
|
273
|
+
*/
|
|
187
274
|
export function useQueries<
|
|
188
275
|
T extends Array<any>,
|
|
189
276
|
TCombinedResult extends QueriesResults<T> = QueriesResults<T>,
|