Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
83 commits
Select commit Hold shift + click to select a range
9859ff3
refactor: updated supported browsers
TkDodo Jan 5, 2023
55e3394
refactor: switch to private fields and methods
TkDodo Jan 5, 2023
5ede052
refactor: remove getAbortController function
TkDodo Jan 5, 2023
e577cc4
refactor: make updateResult private
TkDodo Jan 5, 2023
c60fafe
this didn't work
TkDodo Jan 5, 2023
f9b7eb5
refactor: remove/move/inline some code
TkDodo Jan 5, 2023
0efc1c9
tests: focusManager
TkDodo Jan 5, 2023
0832d01
tests: mutationCache
TkDodo Jan 5, 2023
747a2b5
refactor: mutationObserver
TkDodo Jan 5, 2023
8b03b86
refactor: mutation.setState
TkDodo Jan 6, 2023
08005c1
test(mutations): rewrite test to not rely on internals
TkDodo Jan 6, 2023
80c5252
tests: onlineManager
TkDodo Jan 7, 2023
3cb8103
tests: remove test for a case that cannot happen
TkDodo Jan 7, 2023
2ffc6c9
refactor(core): make initialState and revertState private
TkDodo Jan 7, 2023
c49d66c
tests: rewrite query tests to not depend on internals
TkDodo Jan 7, 2023
cac35bc
tests: rewrite queryCache tests to not depend on internals
TkDodo Jan 7, 2023
2906469
refactor: notifyOptions.cache
TkDodo Jan 7, 2023
31252c5
chore: remove unused imports
TkDodo Jan 7, 2023
552ee30
refactor: unify partialMatchKey and partialDeepEqual
TkDodo Jan 7, 2023
a4bba9e
refactor: remove Array check when checking for keys during filtering
TkDodo Jan 7, 2023
c4a2eb8
refactor: rename hashQueryKey to hashKey
TkDodo Jan 7, 2023
aa7a3fe
tests: remove unnecessary condition
TkDodo Jan 7, 2023
ac8184c
tests: get rid of annoying false-positive console.error log
TkDodo Jan 7, 2023
4968b1e
tests: don't rely on internals
TkDodo Jan 7, 2023
5a8b368
docs: document size improvements
TkDodo Jan 7, 2023
5a309d3
tests: fix copyButton test
TkDodo Jan 7, 2023
6a343a9
Merge branch 'v5' into feature/size-improvements
TkDodo Jan 7, 2023
f068894
feat: reset mutation variables in success / error case
TkDodo Jan 11, 2023
71124d7
feat: reset mutation variables in success / error case
TkDodo Jan 11, 2023
167b0aa
Merge branch 'v5' into feature/size-improvements
TkDodo Jan 11, 2023
c6b7a9d
Merge branch 'feature/size-improvements' into mutation-refactoring
TkDodo Jan 11, 2023
27a73a3
test(vue-query): fix tests accessing private props
DamianOsipiuk Jan 11, 2023
a42f974
feat: add useMutationVariables
TkDodo Jan 12, 2023
76a2bc4
refactor: rename useIsMutating file to useMutationState
TkDodo Jan 12, 2023
bb017c1
refactor: restructure tests
TkDodo Jan 12, 2023
eb369b1
refactor: move getMutationVariables to the query-core
TkDodo Jan 12, 2023
b0e62c7
docs: rewrite optimistic updates example
TkDodo Jan 12, 2023
42c4a57
refactor: don't reset variables
TkDodo Jan 12, 2023
0c8ef53
fix: revert tests back
TkDodo Jan 12, 2023
71986d0
refactor: use optional chaining
TkDodo Jan 12, 2023
6dca646
remove unnecessary condition
TkDodo Jan 13, 2023
6c70e64
refactor: remove defaultOptions from mutation.ts
TkDodo Jan 13, 2023
7085447
Merge branch 'v5' into feature/size-improvements
TkDodo Jan 13, 2023
d923c8a
Merge branch 'feature/size-improvements' into mutation-refactoring
TkDodo Jan 13, 2023
18e6552
Merge branch 'v5' into feature/size-improvements
TkDodo Jan 13, 2023
01d0073
resolve merge conflict
TkDodo Jan 13, 2023
5825568
Merge branch 'feature/size-improvements' into mutation-refactoring
TkDodo Jan 13, 2023
244d1b9
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 13, 2023
abdce2e
refactor: make input to executeMutation required
TkDodo Jan 13, 2023
f2b8dcd
stabilize test
TkDodo Jan 13, 2023
3883194
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 15, 2023
b620192
fix: don't filter out nullish variables
TkDodo Jan 15, 2023
98621bf
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 20, 2023
e8e0515
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 20, 2023
2bc57eb
remove unused export
TkDodo Jan 20, 2023
a5c7db3
fix merge conflict
TkDodo Jan 20, 2023
367a3c6
remove leftover console log
TkDodo Jan 20, 2023
9173dcd
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 22, 2023
c186190
Merge remote-tracking branch 'origin/v5' into mutation-refactoring
TkDodo Jan 23, 2023
d6ae402
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 25, 2023
d1ea076
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 25, 2023
570e410
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 30, 2023
2afecf3
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 30, 2023
4e7c709
feat: expose submittedAt timestamp from useMutation
TkDodo Jan 30, 2023
1d3b3bf
fix a test
TkDodo Jan 30, 2023
2191b3d
test: add submittedAt to test assertions
TkDodo Jan 30, 2023
647e55a
Merge branch 'v5' into mutation-refactoring
TkDodo Jan 30, 2023
1eeaf9d
docs: document new optimistic updates
TkDodo Jan 30, 2023
e61d86c
docs: add `isError` check to optimistic updates example
TkDodo Jan 30, 2023
c02cab8
feat: replace isFetching with status for mutationFilters
TkDodo Jan 30, 2023
f6eb91e
fix: make sure TVariables narrow correctly
TkDodo Jan 30, 2023
609ac95
Merge branch 'v5' into mutation-refactoring
TkDodo Feb 12, 2023
3563147
formatting
TkDodo Feb 12, 2023
a1c0c3d
Merge branch 'v5' into mutation-refactoring
TkDodo Feb 12, 2023
78509ef
stabilize a flaky test
TkDodo Feb 12, 2023
175f8d0
expose useMutationState
TkDodo Feb 12, 2023
b98c96c
docs update
TkDodo Feb 12, 2023
6a71982
Merge remote-tracking branch 'origin/v5' into mutation-refactoring
TkDodo Feb 12, 2023
73d79d7
Merge branch 'v5' into mutation-refactoring
TkDodo Feb 18, 2023
c733726
fix: status 'loading' is no longer a thing
TkDodo Feb 18, 2023
02d23a0
test: mutations don't have `isLoading` anymore
TkDodo Feb 18, 2023
ef83459
Merge branch 'v5' into mutation-refactoring
TkDodo Feb 18, 2023
7fc156e
docs: new features for simplified optimistic updates
TkDodo Feb 18, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,10 @@
"label": "useIsMutating",
"to": "react/reference/useIsMutating"
},
{
"label": "useMutationState",
"to": "react/reference/useMutationState"
},
{
"label": "QueryClient",
"to": "react/reference/QueryClient"
Expand Down
4 changes: 2 additions & 2 deletions docs/react/devtools.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<QueryClient | undefined>`
- 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

Expand Down
5 changes: 2 additions & 3 deletions docs/react/guides/filters.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
32 changes: 32 additions & 0 deletions docs/react/guides/migrating-to-v5.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<ul>
{queryInfo.data.items.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
{addTodoMutation.isPending && (
<li
key={String(addTodoMutation.submittedAt)}
style={{opacity: 0.5}}
>
{addTodoMutation.variables}
</li>
)}
</ul>
)
}
```

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.
Expand Down
98 changes: 91 additions & 7 deletions docs/react/guides/optimistic-updates.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<ul>
{todoQuery.items.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
{isPending && (
<li
key={String(submittedAt)}
style={{ opacity: 0.5 }}
>
{variables}
</li>
)}
</ul>
```
[//]: # '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 && (
<li
key={String(submittedAt)}
style={{ color: 'red' }}
>
{variables}
<button onClick={() => mutate(variables)}>
Retry
</button>
</li>
)}
```
[//]: # '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<string>({
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'

Expand Down Expand Up @@ -42,13 +124,11 @@ useMutation({
},
})
```

[//]: # 'Example'

## Updating a single todo
### Updating a single todo

[//]: # 'Example2'

```tsx
useMutation({
mutationFn: updateTodo,
Expand Down Expand Up @@ -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,
Expand All @@ -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.
2 changes: 0 additions & 2 deletions docs/react/reference/QueryClientProvider.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,3 @@ function App() {
- `client: QueryClient`
- **Required**
- the QueryClient instance to provide
- `context?: React.Context<QueryClient | undefined>`
- Use this to use a custom React Query context. Otherwise, `defaultContext` will be used.
8 changes: 4 additions & 4 deletions docs/react/reference/hydration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<QueryClient | undefined>`
- 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

Expand Down Expand Up @@ -115,7 +115,7 @@ function App() {
- Optional
- `defaultOptions: QueryOptions`
- The default query options to use for the hydrated queries.
- `context?: React.Context<QueryClient | undefined>`
- 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'
4 changes: 2 additions & 2 deletions docs/react/reference/useIsFetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const isFetchingPosts = useIsFetching({ queryKey: ['posts'] })
**Options**

- `filters?: QueryFilters`: [Query Filters](../guides/filters#query-filters)
- `context?: React.Context<QueryClient | undefined>`
- 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**

Expand Down
4 changes: 2 additions & 2 deletions docs/react/reference/useIsMutating.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const isMutatingPosts = useIsMutating({ mutationKey: ['posts'] })
**Options**

- `filters?: MutationFilters`: [Mutation Filters](../guides/filters#mutation-filters)
- `context?: React.Context<QueryClient | undefined>`
- 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**

Expand Down
8 changes: 6 additions & 2 deletions docs/react/reference/useMutation.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
mutateAsync,
reset,
status,
submittedAt
} = useMutation({
mutationFn,
gcTime,
Expand Down Expand Up @@ -90,8 +91,8 @@ mutate(variables, {
- `meta: Record<string, unknown>`
- 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<QueryClient | undefined>`
- 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**

Expand Down Expand Up @@ -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`.

35 changes: 35 additions & 0 deletions docs/react/reference/useMutationState.md
Original file line number Diff line number Diff line change
@@ -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<TResult>`
- Will be an Array of whatever `select` returns for each matching mutation.
4 changes: 2 additions & 2 deletions docs/react/reference/useQueries.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<QueryClient | undefined>`
- 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.

Expand Down
4 changes: 2 additions & 2 deletions docs/react/reference/useQuery.md
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,8 @@ const {
- `meta: Record<string, unknown>`
- 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<QueryClient | undefined>`
- 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**

Expand Down
6 changes: 3 additions & 3 deletions docs/react/reference/useQueryClient.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<QueryClient | undefined>`
- 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.
2 changes: 1 addition & 1 deletion examples/react/auto-refetching/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ function Example() {
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})

if (status === 'loading') return <h1>Loading...</h1>
if (status === 'pending') return <h1>Loading...</h1>
if (status === 'error') return <span>Error: {error.message}</span>

return (
Expand Down
4 changes: 2 additions & 2 deletions examples/react/infinite-query-with-max-pages/pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ function Example() {
<h1>Infinite Query with max pages</h1>
<h3>4 projects per page</h3>
<h3>3 pages max</h3>
{status === 'loading' ? (
{status === 'pending' ? (
<p>Loading...</p>
) : status === 'error' ? (
<span>Error: {error.message}</span>
Expand All @@ -63,7 +63,7 @@ function Example() {
: 'Nothing more to load'}
</button>
</div>
{data?.pages.map((page) => (
{data.pages.map((page) => (
<React.Fragment key={page.nextId}>
{page.data.map((project) => (
<p
Expand Down
Loading