diff --git a/docs/config.json b/docs/config.json
index 6322bc17e66..d399e8c4cc0 100644
--- a/docs/config.json
+++ b/docs/config.json
@@ -349,6 +349,10 @@
"label": "useIsMutating",
"to": "react/reference/useIsMutating"
},
+ {
+ "label": "useMutationState",
+ "to": "react/reference/useMutationState"
+ },
{
"label": "QueryClient",
"to": "react/reference/QueryClient"
diff --git a/docs/react/devtools.md b/docs/react/devtools.md
index 54984d7fa1e..6bdea377fca 100644
--- a/docs/react/devtools.md
+++ b/docs/react/devtools.md
@@ -66,8 +66,8 @@ function App() {
- `panelPosition?: "top" | "bottom" | "left" | "right"`
- Defaults to `bottom`
- The position of the React Query devtools panel
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
## Embedded Mode
diff --git a/docs/react/guides/filters.md b/docs/react/guides/filters.md
index e1588cd3aa8..c55d8f93012 100644
--- a/docs/react/guides/filters.md
+++ b/docs/react/guides/filters.md
@@ -66,8 +66,7 @@ A mutation filter object supports the following properties:
- Set this property to define a mutation key to match on.
- `exact?: boolean`
- If you don't want to search mutations inclusively by mutation key, you can pass the `exact: true` option to return only the mutation with the exact mutation key you have passed.
-- `fetching?: boolean`
- - When set to `true` it will match mutations that are currently fetching.
- - When set to `false` it will match mutations that are not fetching.
+- `status?: MutationStatus`
+ - Allows for filtering mutations according to their status.
- `predicate?: (mutation: Mutation) => boolean`
- This predicate function will be used as a final filter on all matching mutations. If no other filters are specified, this function will be evaluated against every mutation in the cache.
diff --git a/docs/react/guides/migrating-to-v5.md b/docs/react/guides/migrating-to-v5.md
index 055607f30d7..281e431e6c8 100644
--- a/docs/react/guides/migrating-to-v5.md
+++ b/docs/react/guides/migrating-to-v5.md
@@ -323,6 +323,38 @@ To understand the reasoning behing this change checkout the [v5 roadmap discussi
## New Features 🚀
+### Simplified optimistic updates
+
+We have a new, simplified way to perform optimistic updates by leveraging the returned `variables` from `useMutation`:
+
+```tsx
+ const queryInfo = useTodos()
+ const addTodoMutation = useMutation({
+ mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
+ })
+
+ if (queryInfo.data) {
+ return (
+
+ {queryInfo.data.items.map((todo) => (
+
{todo.text}
+ ))}
+ {addTodoMutation.isPending && (
+
+ {addTodoMutation.variables}
+
+ )}
+
+ )
+ }
+```
+
+Here, we are only changing how the UI looks when the mutation is running instead of writing data directly to the cache. This works best if we only have one place where we need to show the optimistic update. For more details, have a look at the [optimistic updates documentation](../guides/optimistic-updates.md).
+
### Eternal list: scalable infinite query with new maxPages option
Infinite queries are great when infinite scroll or pagination are needed.
diff --git a/docs/react/guides/optimistic-updates.md b/docs/react/guides/optimistic-updates.md
index 59aee308078..67a4fc8ef72 100644
--- a/docs/react/guides/optimistic-updates.md
+++ b/docs/react/guides/optimistic-updates.md
@@ -3,11 +3,93 @@ id: optimistic-updates
title: Optimistic Updates
---
+React Query provides two ways to optimistically update your UI before a mutation has completed. You can either use the `onMutate` option to update your cache directly, or leverage the returned `variables` to update your UI from the `useMutation` result.
+
+## Via the UI
+
+This is the simpler variant, as it doesn't interact with the cache directly.
+
+[//]: # 'ExampleUI1'
+```tsx
+ const { isPending, submittedAt, variables, mutate, isError } = useMutation({
+ mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
+ // make sure to _return_ the Promise from the query invalidation
+ // so that the mutation stays in `pending` state until the refetch is finished
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
+ })
+```
+[//]: # 'ExampleUI1'
+
+you will then have access to `addTodoMutation.variables`, which contain the added todo. In your UI list, where the query is rendered, you can append another item to the list while the mutation is `pending`:
+
+[//]: # 'ExampleUI2'
+```tsx
+
+ {todoQuery.items.map((todo) => (
+
{todo.text}
+ ))}
+ {isPending && (
+
+ {variables}
+
+ )}
+
+```
+[//]: # 'ExampleUI2'
+
+The `submittedAt` property is a timestamp that is set when `mutate` is invoked. This is useful to create a unique key for the pending todo item. We've also added an `opacity` to indicate that this item is only temporarily here. Once the mutation completes, the item will be removed because the mutation is no longer `pending`. Given that the refetch succeeded, we should see the item as a "normal item" in our list.
+
+If the mutation errors, the item will also disappear. But we could continue to show it, if we want, by checking for the `isError` state of the mutation. `variables` are _not_ cleared when the mutation errors, so we can still access them, maybe even show a retry button:
+
+[//]: # 'ExampleUI3'
+```tsx
+{isError && (
+
+ {variables}
+
+
+)}
+```
+[//]: # 'ExampleUI3'
+
+### If the mutation and the query don't live in the same component
+
+This approach works very will if the mutation and the query live in the same component, However, you also get access to all mutations in other components via the dedicated `useMurationState` hook. It is best combined with a `mutationKey`:
+
+[//]: # 'ExampleUI4'
+```tsx
+// somewhere in your app
+const { mutate } = useMutation({
+ mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
+ onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
+ mutationKey: ['addTodo']
+})
+
+// access variables somewhere else
+const variables = useMutationState({
+ filters: { mutationKey: ['addTodo'], status: 'pending' },
+ select: (mutation) => mutation.state.variables
+})
+```
+[//]: # 'ExampleUI4'
+
+`variables` will be an `Array`, because there might be multiple mutations running at the same time. This will even make displaying concurrent optimistic updates a breeze.
+
+## Via the cache
+
When you optimistically update your state before performing a mutation, there is a chance that the mutation will fail. In most of these failure cases, you can just trigger a refetch for your optimistic queries to revert them to their true server state. In some circumstances though, refetching may not work correctly and the mutation error could represent some type of server issue that won't make it possible to refetch. In this event, you can instead choose to rollback your update.
To do this, `useMutation`'s `onMutate` handler option allows you to return a value that will later be passed to both `onError` and `onSettled` handlers as the last argument. In most cases, it is most useful to pass a rollback function.
-## Updating a list of todos when adding a new todo
+### Updating a list of todos when adding a new todo
[//]: # 'Example'
@@ -42,13 +124,11 @@ useMutation({
},
})
```
-
[//]: # 'Example'
-## Updating a single todo
+### Updating a single todo
[//]: # 'Example2'
-
```tsx
useMutation({
mutationFn: updateTodo,
@@ -80,13 +160,11 @@ useMutation({
},
})
```
-
[//]: # 'Example2'
You can also use the `onSettled` function in place of the separate `onError` and `onSuccess` handlers if you wish:
[//]: # 'Example3'
-
```tsx
useMutation({
mutationFn: updateTodo,
@@ -98,5 +176,11 @@ useMutation({
},
})
```
-
[//]: # 'Example3'
+
+
+## When to use what
+
+If you only have one place where the optimistic result should be shown, using `variables` and updating the UI directly is the approach that requires less code and is generally easier to reason about. For example, you don't need to handle rollbacks at all.
+
+However, if you have multiple places on the screen that would require to know about the update, manipulating the cache directly will take care of this for you automatically.
diff --git a/docs/react/reference/QueryClientProvider.md b/docs/react/reference/QueryClientProvider.md
index f0be794d89b..08d6d9ec321 100644
--- a/docs/react/reference/QueryClientProvider.md
+++ b/docs/react/reference/QueryClientProvider.md
@@ -20,5 +20,3 @@ function App() {
- `client: QueryClient`
- **Required**
- the QueryClient instance to provide
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
diff --git a/docs/react/reference/hydration.md b/docs/react/reference/hydration.md
index 7e1c17f41f8..ee657a37cb7 100644
--- a/docs/react/reference/hydration.md
+++ b/docs/react/reference/hydration.md
@@ -86,8 +86,8 @@ hydrate(queryClient, dehydratedState, options)
- Optional
- `mutations: MutationOptions` The default mutation options to use for the hydrated mutations.
- `queries: QueryOptions` The default query options to use for the hydrated queries.
- - `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+ - `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
### Limitations
@@ -115,7 +115,7 @@ function App() {
- Optional
- `defaultOptions: QueryOptions`
- The default query options to use for the hydrated queries.
- - `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+ - `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
[//]: # 'HydrationBoundary'
diff --git a/docs/react/reference/useIsFetching.md b/docs/react/reference/useIsFetching.md
index 19b3fe0116a..d35a06a67e1 100644
--- a/docs/react/reference/useIsFetching.md
+++ b/docs/react/reference/useIsFetching.md
@@ -16,8 +16,8 @@ const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
**Options**
- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
**Returns**
diff --git a/docs/react/reference/useIsMutating.md b/docs/react/reference/useIsMutating.md
index 0897fb3438e..7ad18498912 100644
--- a/docs/react/reference/useIsMutating.md
+++ b/docs/react/reference/useIsMutating.md
@@ -16,8 +16,8 @@ const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
**Options**
- `filters?: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
**Returns**
diff --git a/docs/react/reference/useMutation.md b/docs/react/reference/useMutation.md
index c0d455880d1..5c0202e66da 100644
--- a/docs/react/reference/useMutation.md
+++ b/docs/react/reference/useMutation.md
@@ -18,6 +18,7 @@ const {
mutateAsync,
reset,
status,
+ submittedAt
} = useMutation({
mutationFn,
gcTime,
@@ -90,8 +91,8 @@ mutate(variables, {
- `meta: Record`
- Optional
- If set, stores additional information on the mutation cache entry that can be used as needed. It will be accessible wherever the `mutation` is available (eg. `onError`, `onSuccess` functions of the `MutationCache`).
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
**Returns**
@@ -139,4 +140,7 @@ mutate(variables, {
- `failureReason: null | TError`
- The failure reason for the mutation retry.
- Reset to `null` when the mutation succeeds.
+- `submittedAt: number`
+ - The timestamp for when the mutation was submitted.
+ - Defaults to `0`.
diff --git a/docs/react/reference/useMutationState.md b/docs/react/reference/useMutationState.md
new file mode 100644
index 00000000000..1850cf2b613
--- /dev/null
+++ b/docs/react/reference/useMutationState.md
@@ -0,0 +1,35 @@
+---
+id: useMutationState
+title: useMutationState
+---
+
+`useMutationState` is a hook that gives you access to all mutations in the `MutationCache`. You can pass `filters` to it to narrow down your mutations, and `select` to transform the mutation state.
+
+```tsx
+import { useMutationState } from '@tanstack/react-query'
+// Get all variables of all running mutations
+const variables = useMutationState({
+ filters: { status: 'pending' },
+ select: (mutation) => mutation.state.variables,
+})
+
+// Get all data of all "post" mutations
+const data = useMutationState({
+ filters: { mutationKey: ['posts'] },
+ select: (mutation) => mutation.state.data,
+})
+```
+
+**Options**
+
+- `options`
+ - `filters?: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
+ - `select?: (mutation: Mutation) => TResult`
+ - Use this to transform the mutation state.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
+
+**Returns**
+
+- `Array`
+ - Will be an Array of whatever `select` returns for each matching mutation.
diff --git a/docs/react/reference/useQueries.md b/docs/react/reference/useQueries.md
index bb203961e48..87e6344e8d0 100644
--- a/docs/react/reference/useQueries.md
+++ b/docs/react/reference/useQueries.md
@@ -18,8 +18,8 @@ const results = useQueries({
The `useQueries` hook accepts an options object with a **queries** key whose value is an array with query option objects identical to the [`useQuery` hook](../reference/useQuery) (excluding the `context` option).
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
> Having the same query key more than once in the array of query objects may cause some data to be shared between queries, e.g. when using `placeholderData` and `select`. To avoid this, consider de-duplicating the queries and map the results back to the desired structure.
diff --git a/docs/react/reference/useQuery.md b/docs/react/reference/useQuery.md
index 8eb0392d500..39065e3f22e 100644
--- a/docs/react/reference/useQuery.md
+++ b/docs/react/reference/useQuery.md
@@ -179,8 +179,8 @@ const {
- `meta: Record`
- Optional
- If set, stores additional information on the query cache entry that can be used as needed. It will be accessible wherever the `query` is available, and is also part of the `QueryFunctionContext` provided to the `queryFn`.
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
**Returns**
diff --git a/docs/react/reference/useQueryClient.md b/docs/react/reference/useQueryClient.md
index 36091b33224..e3b55206f70 100644
--- a/docs/react/reference/useQueryClient.md
+++ b/docs/react/reference/useQueryClient.md
@@ -8,10 +8,10 @@ The `useQueryClient` hook returns the current `QueryClient` instance.
```tsx
import { useQueryClient } from '@tanstack/react-query'
-const queryClient = useQueryClient({ context })
+const queryClient = useQueryClient(queryClient?: QueryClient)
```
**Options**
-- `context?: React.Context`
- - Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
+- `queryClient?: QueryClient`,
+ - Use this to use a custom QueryClient. Otherwise, the one from the nearest context will be used.
diff --git a/examples/react/auto-refetching/pages/index.js b/examples/react/auto-refetching/pages/index.js
index 22f36954b26..09831ec7d87 100755
--- a/examples/react/auto-refetching/pages/index.js
+++ b/examples/react/auto-refetching/pages/index.js
@@ -47,7 +47,7 @@ function Example() {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})
- if (status === 'loading') return
Loading...
+ if (status === 'pending') return
Loading...
if (status === 'error') return Error: {error.message}
return (
diff --git a/examples/react/infinite-query-with-max-pages/pages/index.js b/examples/react/infinite-query-with-max-pages/pages/index.js
index 99c730f7909..4c520a8de53 100755
--- a/examples/react/infinite-query-with-max-pages/pages/index.js
+++ b/examples/react/infinite-query-with-max-pages/pages/index.js
@@ -45,7 +45,7 @@ function Example() {
@@ -86,7 +86,7 @@ function Example() {
{
// Since the last page's data potentially sticks around between page requests,
// we can use `isFetching` to show a background loading
- // indicator since our `status === 'loading'` state won't be triggered
+ // indicator since our `status === 'pending'` state won't be triggered
isFetching ? Loading... : null
}{' '}
diff --git a/examples/react/prefetching/pages/[user]/[repo].js b/examples/react/prefetching/pages/[user]/[repo].js
index 33c3253ef97..4045cc6dde1 100755
--- a/examples/react/prefetching/pages/[user]/[repo].js
+++ b/examples/react/prefetching/pages/[user]/[repo].js
@@ -16,7 +16,7 @@ export default () => {
return (