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 ( + + ) + } +``` + +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 + +``` +[//]: # '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() {

    Infinite Query with max pages

    4 projects per page

    3 pages max

    - {status === 'loading' ? ( + {status === 'pending' ? (

    Loading...

    ) : status === 'error' ? ( Error: {error.message} @@ -63,7 +63,7 @@ function Example() { : 'Nothing more to load'} - {data?.pages.map((page) => ( + {data.pages.map((page) => ( {page.data.map((project) => (

    Infinite Loading

    - {status === 'loading' ? ( + {status === 'pending' ? (

    Loading...

    ) : status === 'error' ? ( Error: {error.message} diff --git a/examples/react/optimistic-updates-typescript/next-env.d.ts b/examples/react/optimistic-updates-typescript/next-env.d.ts index 7b7aa2c7727..4f11a03dc6c 100644 --- a/examples/react/optimistic-updates-typescript/next-env.d.ts +++ b/examples/react/optimistic-updates-typescript/next-env.d.ts @@ -1,2 +1,5 @@ /// -/// +/// + +// NOTE: This file should not be edited +// see https://nextjs.org/docs/basic-features/typescript for more information. diff --git a/examples/react/optimistic-updates-typescript/pages/index.tsx b/examples/react/optimistic-updates-typescript/pages/index.tsx index f3b30e9d7ee..c25694a53f6 100755 --- a/examples/react/optimistic-updates-typescript/pages/index.tsx +++ b/examples/react/optimistic-updates-typescript/pages/index.tsx @@ -35,41 +35,8 @@ function Example() { const { isFetching, ...queryInfo } = useTodos() const addTodoMutation = useMutation({ - mutationFn: (newTodo) => axios.post('/api/data', { text: newTodo }), - // When mutate is called: - onMutate: async (newTodo: string) => { - setText('') - // Cancel any outgoing refetches - // (so they don't overwrite our optimistic update) - await queryClient.cancelQueries({ queryKey: ['todos'] }) - - // Snapshot the previous value - const previousTodos = queryClient.getQueryData(['todos']) - - // Optimistically update to the new value - if (previousTodos) { - queryClient.setQueryData(['todos'], { - ...previousTodos, - items: [ - ...previousTodos.items, - { id: Math.random().toString(), text: newTodo }, - ], - }) - } - - return { previousTodos } - }, - // If the mutation fails, - // use the context returned from onMutate to roll back - onError: (err, variables, context) => { - if (context?.previousTodos) { - queryClient.setQueryData(['todos'], context.previousTodos) - } - }, - // Always refetch after error or success: - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['todos'] }) - }, + mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }), + onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }), }) return ( @@ -85,6 +52,7 @@ function Example() {
    { e.preventDefault() + setText('') addTodoMutation.mutate(text) }} > @@ -106,6 +74,29 @@ function Example() { {queryInfo.data.items.map((todo) => (
  • {todo.text}
  • ))} + {addTodoMutation.isPending && ( +
  • + {addTodoMutation.variables} +
  • + )} + {addTodoMutation.isError && ( +
  • + {addTodoMutation.variables} + +
  • + )} {isFetching &&
    Updating in background...
    } diff --git a/examples/react/optimistic-updates-typescript/tsconfig.json b/examples/react/optimistic-updates-typescript/tsconfig.json index 1087618126c..7f1edf84a63 100644 --- a/examples/react/optimistic-updates-typescript/tsconfig.json +++ b/examples/react/optimistic-updates-typescript/tsconfig.json @@ -18,7 +18,8 @@ "module": "esnext", "moduleResolution": "node", "resolveJsonModule": true, - "isolatedModules": true + "isolatedModules": true, + "incremental": true }, "exclude": [ "node_modules" diff --git a/examples/react/pagination/pages/index.js b/examples/react/pagination/pages/index.js index 41693acfffd..6206f8547fd 100644 --- a/examples/react/pagination/pages/index.js +++ b/examples/react/pagination/pages/index.js @@ -55,7 +55,7 @@ function Example() { instantaneously while they are also refetched invisibly in the background.

    - {status === 'loading' ? ( + {status === 'pending' ? (
    Loading...
    ) : status === 'error' ? (
    Error: {error.message}
    @@ -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 (

    {id}

    - {status === 'loading' ? ( + {status === 'pending' ? ( 'Loading...' ) : status === 'error' ? ( Error: {error.message} diff --git a/examples/solid/basic-graphql-request/src/index.tsx b/examples/solid/basic-graphql-request/src/index.tsx index b8f8eb3abab..9e52205dd8c 100644 --- a/examples/solid/basic-graphql-request/src/index.tsx +++ b/examples/solid/basic-graphql-request/src/index.tsx @@ -69,7 +69,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -142,7 +142,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/solid/basic-typescript/src/index.tsx b/examples/solid/basic-typescript/src/index.tsx index 1334ac9a53c..52bd01994ce 100644 --- a/examples/solid/basic-typescript/src/index.tsx +++ b/examples/solid/basic-typescript/src/index.tsx @@ -45,7 +45,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -113,7 +113,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/solid/default-query-function/src/index.tsx b/examples/solid/default-query-function/src/index.tsx index d70b15dfe14..a2b6ccf3d74 100644 --- a/examples/solid/default-query-function/src/index.tsx +++ b/examples/solid/default-query-function/src/index.tsx @@ -60,7 +60,7 @@ function Posts(props: { setPostId: Setter }) {

    Posts

    - Loading... + Loading... Error: {(state.error as Error).message} @@ -114,7 +114,7 @@ function Post(props: { postId: number; setPostId: Setter }) {
    - + Loading... diff --git a/examples/svelte/basic/src/lib/Posts.svelte b/examples/svelte/basic/src/lib/Posts.svelte index 83b4112f66b..c4f2f2c6427 100644 --- a/examples/svelte/basic/src/lib/Posts.svelte +++ b/examples/svelte/basic/src/lib/Posts.svelte @@ -17,7 +17,7 @@
    - {#if $posts.status === 'loading'} + {#if $posts.status === 'pending'} Loading... {:else if $posts.status === 'error'} Error: {$posts.error.message} diff --git a/examples/svelte/playground/src/routes/AddTodo.svelte b/examples/svelte/playground/src/routes/AddTodo.svelte index c92fc2e47f7..88a71b7cf32 100644 --- a/examples/svelte/playground/src/routes/AddTodo.svelte +++ b/examples/svelte/playground/src/routes/AddTodo.svelte @@ -38,17 +38,17 @@
    - +
    - {$addMutation.status === 'loading' + {$addMutation.status === 'pending' ? 'Saving...' : $addMutation.status === 'error' ? $addMutation.error.message diff --git a/examples/svelte/playground/src/routes/EditTodo.svelte b/examples/svelte/playground/src/routes/EditTodo.svelte index fdf249a3349..24d7992e009 100644 --- a/examples/svelte/playground/src/routes/EditTodo.svelte +++ b/examples/svelte/playground/src/routes/EditTodo.svelte @@ -70,7 +70,7 @@ } $: disableEditSave = - $query.status === 'loading' || $saveMutation.status === 'loading' + $query.status === 'pending' || $saveMutation.status === 'pending'
    @@ -80,7 +80,7 @@ "{$query.data.name}" (#{$editingIndex}) {/if}
    - {#if $query.status === 'loading'} + {#if $query.status === 'pending'} Loading... (Attempt: {$query.failureCount + 1}) {:else if $query.error} @@ -99,7 +99,7 @@
    - {$saveMutation.status === 'loading' + {$saveMutation.status === 'pending' ? 'Saving...' : $saveMutation.status === 'error' ? $saveMutation.error.message diff --git a/examples/svelte/playground/src/routes/Todos.svelte b/examples/svelte/playground/src/routes/Todos.svelte index f3537d7c50f..1346fa722e2 100644 --- a/examples/svelte/playground/src/routes/Todos.svelte +++ b/examples/svelte/playground/src/routes/Todos.svelte @@ -40,7 +40,7 @@
    -{#if $query.status === 'loading'} +{#if $query.status === 'pending'} Loading... (Attempt: {$query.failureCount + 1}) {:else if $query.status === 'error'} diff --git a/examples/svelte/ssr/src/lib/Posts.svelte b/examples/svelte/ssr/src/lib/Posts.svelte index 83b4112f66b..c4f2f2c6427 100644 --- a/examples/svelte/ssr/src/lib/Posts.svelte +++ b/examples/svelte/ssr/src/lib/Posts.svelte @@ -17,7 +17,7 @@
    - {#if $posts.status === 'loading'} + {#if $posts.status === 'pending'} Loading... {:else if $posts.status === 'error'} Error: {$posts.error.message} diff --git a/examples/svelte/star-wars/src/routes/characters/+page.svelte b/examples/svelte/star-wars/src/routes/characters/+page.svelte index 77f868d693f..0fef65bd7a1 100644 --- a/examples/svelte/star-wars/src/routes/characters/+page.svelte +++ b/examples/svelte/star-wars/src/routes/characters/+page.svelte @@ -12,7 +12,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte b/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte index 624ee7dece4..6743ccbcb5f 100644 --- a/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte +++ b/examples/svelte/star-wars/src/routes/characters/[characterId]/+page.svelte @@ -19,7 +19,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/films/+page.svelte b/examples/svelte/star-wars/src/routes/films/+page.svelte index 3a7cb247130..adb251e0d23 100644 --- a/examples/svelte/star-wars/src/routes/films/+page.svelte +++ b/examples/svelte/star-wars/src/routes/films/+page.svelte @@ -12,7 +12,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte b/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte index 988ccc6ad59..5342487a6ee 100644 --- a/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte +++ b/examples/svelte/star-wars/src/routes/films/[filmId]/+page.svelte @@ -18,7 +18,7 @@ }) -{#if $query.status === 'loading'} +{#if $query.status === 'pending'}

    Loading...

    {/if} diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index a81795c3a7a..387800c5535 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -19,7 +19,6 @@ interface MutationConfig { options: MutationOptions defaultOptions?: MutationOptions state?: MutationState - meta?: MutationMeta } export interface MutationState< @@ -36,6 +35,7 @@ export interface MutationState< isPaused: boolean status: MutationStatus variables: TVariables | undefined + submittedAt: number } interface FailedAction { @@ -85,8 +85,8 @@ export class Mutation< TContext = unknown, > extends Removable { state: MutationState - options: MutationOptions - mutationId: number + readonly options: MutationOptions + readonly mutationId: number #observers: MutationObserver[] #mutationCache: MutationCache @@ -95,10 +95,7 @@ export class Mutation< constructor(config: MutationConfig) { super() - this.options = { - ...config.defaultOptions, - ...config.options, - } + this.options = config.options this.mutationId = config.mutationId this.#mutationCache = config.mutationCache this.#observers = [] @@ -150,17 +147,21 @@ export class Mutation< } continue(): Promise { - return this.#retryer?.continue() ?? this.execute() + return ( + this.#retryer?.continue() ?? + // continuing a mutation assumes that variables are set, mutation must have been dehydrated before + this.execute(this.state.variables!) + ) } - async execute(): Promise { + async execute(variables: TVariables): Promise { const executeMutation = () => { this.#retryer = createRetryer({ fn: () => { if (!this.options.mutationFn) { return Promise.reject(new Error('No mutationFn found')) } - return this.options.mutationFn(this.state.variables!) + return this.options.mutationFn(variables) }, onFail: (failureCount, error) => { this.#dispatch({ type: 'failed', failureCount, error }) @@ -180,20 +181,21 @@ export class Mutation< } const restored = this.state.status === 'pending' + try { if (!restored) { - this.#dispatch({ type: 'pending', variables: this.options.variables! }) + this.#dispatch({ type: 'pending', variables }) // Notify cache callback await this.#mutationCache.config.onMutate?.( - this.state.variables, + variables, this as Mutation, ) - const context = await this.options.onMutate?.(this.state.variables!) + const context = await this.options.onMutate?.(variables) if (context !== this.state.context) { this.#dispatch({ type: 'pending', context, - variables: this.state.variables, + variables, }) } } @@ -202,23 +204,14 @@ export class Mutation< // Notify cache callback await this.#mutationCache.config.onSuccess?.( data, - this.state.variables, + variables, this.state.context, this as Mutation, ) - await this.options.onSuccess?.( - data, - this.state.variables!, - this.state.context!, - ) + await this.options.onSuccess?.(data, variables, this.state.context!) - await this.options.onSettled?.( - data, - null, - this.state.variables!, - this.state.context, - ) + await this.options.onSettled?.(data, null, variables, this.state.context) this.#dispatch({ type: 'success', data }) return data @@ -227,21 +220,21 @@ export class Mutation< // Notify cache callback await this.#mutationCache.config.onError?.( error, - this.state.variables, + variables, this.state.context, this as Mutation, ) await this.options.onError?.( error as TError, - this.state.variables!, + variables, this.state.context, ) await this.options.onSettled?.( undefined, error as TError, - this.state.variables!, + variables, this.state.context, ) throw error @@ -283,6 +276,7 @@ export class Mutation< isPaused: !canFetch(this.options.networkMode), status: 'pending', variables: action.variables, + submittedAt: Date.now(), } case 'success': return { @@ -336,5 +330,6 @@ export function getDefaultState< isPaused: false, status: 'idle', variables: undefined, + submittedAt: 0, } } diff --git a/packages/query-core/src/mutationCache.ts b/packages/query-core/src/mutationCache.ts index f9887f5562b..210fe839232 100644 --- a/packages/query-core/src/mutationCache.ts +++ b/packages/query-core/src/mutationCache.ts @@ -95,9 +95,6 @@ export class MutationCache extends Subscribable { mutationId: ++this.#mutationId, options: client.defaultMutationOptions(options), state, - defaultOptions: options.mutationKey - ? client.getMutationDefaults(options.mutationKey) - : undefined, }) this.add(mutation) @@ -142,7 +139,7 @@ export class MutationCache extends Subscribable { return this.#mutations.find((mutation) => matchMutation(filters, mutation)) } - findAll(filters: MutationFilters): Mutation[] { + findAll(filters: MutationFilters = {}): Mutation[] { return this.#mutations.filter((mutation) => matchMutation(filters, mutation), ) diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 0f8f7c13de3..4778963cb35 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -5,7 +5,6 @@ import type { QueryClient } from './queryClient' import { Subscribable } from './subscribable' import type { MutateOptions, - MutationObserverBaseResult, MutationObserverResult, MutationObserverOptions, RegisteredError, @@ -18,11 +17,6 @@ type MutationObserverListener = ( result: MutationObserverResult, ) => void -interface NotifyOptions { - onError?: boolean - onSuccess?: boolean -} - // CLASS export class MutationObserver< @@ -81,16 +75,7 @@ export class MutationObserver< onMutationUpdate(action: Action): void { this.#updateResult() - // Determine which callbacks to trigger - const notifyOptions: NotifyOptions = {} - - if (action.type === 'success') { - notifyOptions.onSuccess = true - } else if (action.type === 'error') { - notifyOptions.onError = true - } - - this.#notify(notifyOptions) + this.#notify(action) } getCurrentResult(): MutationObserverResult< @@ -105,43 +90,34 @@ export class MutationObserver< reset(): void { this.#currentMutation = undefined this.#updateResult() - this.#notify({}) + this.#notify() } mutate( - variables?: TVariables, + variables: TVariables, options?: MutateOptions, ): Promise { this.#mutateOptions = options - if (this.#currentMutation) { - this.#currentMutation.removeObserver(this) - } + this.#currentMutation?.removeObserver(this) this.#currentMutation = this.#client .getMutationCache() .build(this.#client, { ...this.options, - variables: - typeof variables !== 'undefined' ? variables : this.options.variables, }) this.#currentMutation.addObserver(this) - return this.#currentMutation.execute() + return this.#currentMutation.execute(variables) } #updateResult(): void { - const state = this.#currentMutation - ? this.#currentMutation.state - : getDefaultState() - - const result: MutationObserverBaseResult< - TData, - TError, - TVariables, - TContext - > = { + const state = + this.#currentMutation?.state ?? + getDefaultState() + + this.#currentResult = { ...state, isPending: state.status === 'pending', isSuccess: state.status === 'success', @@ -149,41 +125,34 @@ export class MutationObserver< isIdle: state.status === 'idle', mutate: this.mutate, reset: this.reset, - } - - this.#currentResult = result as MutationObserverResult< - TData, - TError, - TVariables, - TContext - > + } as MutationObserverResult } - #notify(options: NotifyOptions) { + #notify(action?: Action): void { notifyManager.batch(() => { // First trigger the mutate callbacks if (this.#mutateOptions && this.hasListeners()) { - if (options.onSuccess) { + if (action?.type === 'success') { this.#mutateOptions.onSuccess?.( - this.#currentResult.data!, + action.data, this.#currentResult.variables!, this.#currentResult.context!, ) this.#mutateOptions.onSettled?.( - this.#currentResult.data!, + action.data, null, this.#currentResult.variables!, this.#currentResult.context, ) - } else if (options.onError) { + } else if (action?.type === 'error') { this.#mutateOptions.onError?.( - this.#currentResult.error!, + action.error, this.#currentResult.variables!, this.#currentResult.context, ) this.#mutateOptions.onSettled?.( undefined, - this.#currentResult.error, + action.error, this.#currentResult.variables!, this.#currentResult.context, ) diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index d6cab58fa89..73c2f888254 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -259,9 +259,7 @@ export class Query< onFocus(): void { const observer = this.#observers.find((x) => x.shouldFetchOnWindowFocus()) - if (observer) { - observer.refetch({ cancelRefetch: false }) - } + observer?.refetch({ cancelRefetch: false }) // Continue fetch if currently paused this.#retryer?.continue() @@ -270,9 +268,7 @@ export class Query< onOnline(): void { const observer = this.#observers.find((x) => x.shouldFetchOnReconnect()) - if (observer) { - observer.refetch({ cancelRefetch: false }) - } + observer?.refetch({ cancelRefetch: false }) // Continue fetch if currently paused this.#retryer?.continue() diff --git a/packages/query-core/src/queryClient.ts b/packages/query-core/src/queryClient.ts index 64376438f7c..e3f004e3907 100644 --- a/packages/query-core/src/queryClient.ts +++ b/packages/query-core/src/queryClient.ts @@ -103,7 +103,7 @@ export class QueryClient { } isMutating(filters?: MutationFilters): number { - return this.#mutationCache.findAll({ ...filters, fetching: true }).length + return this.#mutationCache.findAll({ ...filters, status: 'pending' }).length } getQueryData( diff --git a/packages/query-core/src/tests/hydration.test.tsx b/packages/query-core/src/tests/hydration.test.tsx index 5086d0001e7..c78a6643cda 100644 --- a/packages/query-core/src/tests/hydration.test.tsx +++ b/packages/query-core/src/tests/hydration.test.tsx @@ -364,10 +364,13 @@ describe('dehydration and rehydration', () => { retryDelay: 10, }) - executeMutation(serverClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + serverClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) await sleep(50) @@ -433,10 +436,13 @@ describe('dehydration and rehydration', () => { retry: false, }) - executeMutation(queryClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + queryClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) await sleep(1) const dehydrated = dehydrate(queryClient, { dehydrateMutations: false }) @@ -463,10 +469,13 @@ describe('dehydration and rehydration', () => { retryDelay: 20, }) - executeMutation(queryClient, { - mutationKey: ['addTodo'], - variables: { text: 'text' }, - }).catch(() => undefined) + executeMutation( + queryClient, + { + mutationKey: ['addTodo'], + }, + { text: 'text' }, + ).catch(() => undefined) // Dehydrate mutation between retries await sleep(1) diff --git a/packages/query-core/src/tests/mutationCache.test.tsx b/packages/query-core/src/tests/mutationCache.test.tsx index bdd7d4049b8..fb1e2851b65 100644 --- a/packages/query-core/src/tests/mutationCache.test.tsx +++ b/packages/query-core/src/tests/mutationCache.test.tsx @@ -11,12 +11,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.reject(new Error('error')), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.reject(new Error('error')), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -40,16 +43,19 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.reject(new Error('error')), - onError: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.reject(new Error('error')), + onError: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) } catch {} expect(states).toEqual([1, 2, 3, 4]) @@ -63,12 +69,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -90,16 +99,19 @@ describe('mutationCache', () => { const testCache = new MutationCache({ onSuccess }) const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onSuccess: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onSuccess: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) expect(states).toEqual([1, 2, 3, 4]) }) @@ -112,12 +124,15 @@ describe('mutationCache', () => { const testClient = createQueryClient({ mutationCache: testCache }) try { - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: () => 'context', - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: () => 'context', + }, + 'vars', + ) } catch {} const mutation = testCache.getAll()[0] @@ -135,16 +150,19 @@ describe('mutationCache', () => { const testCache = new MutationCache({ onMutate }) const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve({ data: 5 }), - onMutate: async () => { - states.push(3) - await sleep(1) - states.push(4) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve({ data: 5 }), + onMutate: async () => { + states.push(3) + await sleep(1) + states.push(4) + }, }, - }) + 'vars', + ) expect(states).toEqual([1, 2, 3, 4]) }) @@ -155,11 +173,14 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const key = ['mutation', 'vars'] - await executeMutation(testClient, { - mutationKey: key, - variables: 'vars', - mutationFn: () => Promise.resolve(), - }) + await executeMutation( + testClient, + { + mutationKey: key, + mutationFn: () => Promise.resolve(), + }, + 'vars', + ) const [mutation] = testCache.getAll() expect(testCache.find({ mutationKey: key })).toEqual(mutation) expect( @@ -167,7 +188,9 @@ describe('mutationCache', () => { ).toEqual(mutation) expect(testCache.find({ mutationKey: ['unknown'] })).toEqual(undefined) expect( - testCache.find({ predicate: (m) => m.options.variables === 'vars' }), + testCache.find({ + predicate: (m) => m.options.mutationKey?.[0] === key[0], + }), ).toEqual(mutation) }) }) @@ -176,30 +199,42 @@ describe('mutationCache', () => { test('should filter correctly', async () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) - await executeMutation(testClient, { - mutationKey: ['a', 1], - variables: 1, - mutationFn: () => Promise.resolve(), - }) - await executeMutation(testClient, { - mutationKey: ['a', 2], - variables: 2, - mutationFn: () => Promise.resolve(), - }) - await executeMutation(testClient, { - mutationKey: ['b'], - mutationFn: () => Promise.resolve(), - }) + await executeMutation( + testClient, + { + mutationKey: ['a', 1], + mutationFn: () => Promise.resolve(), + }, + 1, + ) + await executeMutation( + testClient, + { + mutationKey: ['a', 2], + mutationFn: () => Promise.resolve(), + }, + 2, + ) + await executeMutation( + testClient, + { + mutationKey: ['b'], + mutationFn: () => Promise.resolve(), + }, + 3, + ) const [mutation1, mutation2] = testCache.getAll() expect( testCache.findAll({ mutationKey: ['a'], exact: false }), ).toHaveLength(2) expect(testCache.find({ mutationKey: ['a', 1] })).toEqual(mutation1) - expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([]) expect( - testCache.findAll({ predicate: (m) => m.options.variables === 2 }), + testCache.findAll({ + predicate: (m) => m.options.mutationKey?.[1] === 2, + }), ).toEqual([mutation2]) + expect(testCache.findAll({ mutationKey: ['unknown'] })).toEqual([]) }) }) @@ -208,13 +243,16 @@ describe('mutationCache', () => { const testCache = new MutationCache() const testClient = createQueryClient({ mutationCache: testCache }) const onSuccess = jest.fn() - await executeMutation(testClient, { - mutationKey: ['a', 1], - variables: 1, - gcTime: 10, - mutationFn: () => Promise.resolve(), - onSuccess, - }) + await executeMutation( + testClient, + { + mutationKey: ['a', 1], + gcTime: 10, + mutationFn: () => Promise.resolve(), + onSuccess, + }, + 1, + ) expect(testCache.getAll()).toHaveLength(1) await sleep(10) @@ -227,9 +265,8 @@ describe('mutationCache', () => { test('should not remove mutations if there are active observers', async () => { const queryClient = createQueryClient() const observer = new MutationObserver(queryClient, { - variables: 1, gcTime: 10, - mutationFn: () => Promise.resolve(), + mutationFn: (input: number) => Promise.resolve(input), }) const unsubscribe = observer.subscribe(() => undefined) @@ -250,7 +287,6 @@ describe('mutationCache', () => { const queryClient = createQueryClient() const onSuccess = jest.fn() const observer = new MutationObserver(queryClient, { - variables: 1, gcTime: 10, mutationFn: async () => { await sleep(20) @@ -277,7 +313,6 @@ describe('mutationCache', () => { const queryClient = createQueryClient() const onSuccess = jest.fn() const observer = new MutationObserver(queryClient, { - variables: 1, gcTime: 0, mutationFn: async () => { return 'data' diff --git a/packages/query-core/src/tests/mutationObserver.test.tsx b/packages/query-core/src/tests/mutationObserver.test.tsx index 1ca53454005..7af9534222a 100644 --- a/packages/query-core/src/tests/mutationObserver.test.tsx +++ b/packages/query-core/src/tests/mutationObserver.test.tsx @@ -29,7 +29,7 @@ describe('mutationObserver', () => { const unsubscribe1 = mutation.subscribe(subscription1Handler) const unsubscribe2 = mutation.subscribe(subscription2Handler) - mutation.mutate() + mutation.mutate('input') unsubscribe1() diff --git a/packages/query-core/src/tests/mutations.test.tsx b/packages/query-core/src/tests/mutations.test.tsx index c3a31a27e4d..7851e301c74 100644 --- a/packages/query-core/src/tests/mutations.test.tsx +++ b/packages/query-core/src/tests/mutations.test.tsx @@ -15,15 +15,6 @@ describe('mutations', () => { queryClient.clear() }) - test('mutate should trigger a mutation', async () => { - const result = await executeMutation(queryClient, { - mutationFn: async (text: string) => text, - variables: 'todo', - }) - - expect(result).toBe(result) - }) - test('mutate should accept null values', async () => { let variables @@ -34,26 +25,29 @@ describe('mutations', () => { }, }) - mutation.mutate(null) - - await sleep(10) + await mutation.mutate(null) expect(variables).toBe(null) }) test('setMutationDefaults should be able to set defaults', async () => { const key = queryKey() + const fn = jest.fn() queryClient.setMutationDefaults(key, { - mutationFn: async (text: string) => text, + mutationFn: fn, }) - const result = await executeMutation(queryClient, { - mutationKey: key, - variables: 'todo', - }) + await executeMutation( + queryClient, + { + mutationKey: key, + }, + 'vars', + ) - expect(result).toBe(result) + expect(fn).toHaveBeenCalledTimes(1) + expect(fn).toHaveBeenCalledWith('vars') }) test('mutation should set correct success states', async () => { @@ -63,7 +57,6 @@ describe('mutations', () => { return text }, onMutate: (text) => text, - variables: 'todo', }) expect(mutation.getCurrentResult()).toEqual({ @@ -81,6 +74,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'idle', variables: undefined, + submittedAt: 0, }) const states: MutationState[] = [] @@ -89,7 +83,7 @@ describe('mutations', () => { states.push(state) }) - mutation.mutate() + mutation.mutate('todo') await sleep(0) @@ -108,6 +102,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'pending', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(5) @@ -127,6 +122,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'pending', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(20) @@ -146,17 +142,17 @@ describe('mutations', () => { reset: expect.any(Function), status: 'success', variables: 'todo', + submittedAt: expect.any(Number), }) }) test('mutation should set correct error states', async () => { const mutation = new MutationObserver(queryClient, { - mutationFn: async () => { + mutationFn: async (_: string) => { await sleep(20) return Promise.reject(new Error('err')) }, onMutate: (text) => text, - variables: 'todo', retry: 1, retryDelay: 1, }) @@ -167,7 +163,7 @@ describe('mutations', () => { states.push(state) }) - mutation.mutate().catch(() => undefined) + mutation.mutate('todo').catch(() => undefined) await sleep(0) @@ -186,6 +182,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'pending', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(10) @@ -205,6 +202,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'pending', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(20) @@ -224,6 +222,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'pending', variables: 'todo', + submittedAt: expect.any(Number), }) await sleep(30) @@ -243,6 +242,7 @@ describe('mutations', () => { reset: expect.any(Function), status: 'error', variables: 'todo', + submittedAt: expect.any(Number), }) }) @@ -276,6 +276,7 @@ describe('mutations', () => { isPaused: true, status: 'pending', variables: 'todo', + submittedAt: 1, }, ) @@ -288,6 +289,7 @@ describe('mutations', () => { isPaused: true, status: 'pending', variables: 'todo', + submittedAt: 1, }) await queryClient.resumePausedMutations() @@ -301,6 +303,7 @@ describe('mutations', () => { isPaused: false, status: 'success', variables: 'todo', + submittedAt: 1, }) expect(onMutate).not.toHaveBeenCalled() diff --git a/packages/query-core/src/tests/utils.ts b/packages/query-core/src/tests/utils.ts index 438510b7bc0..5713546ab39 100644 --- a/packages/query-core/src/tests/utils.ts +++ b/packages/query-core/src/tests/utils.ts @@ -41,17 +41,15 @@ export function setActTimeout(fn: () => void, ms?: number) { */ export const expectType = (_: T): void => undefined -/** - * Assert the parameter is not typed as `any` - */ -export const expectTypeNotAny = (_: 0 extends 1 & T ? never : T): void => - undefined - -export const executeMutation = ( +export const executeMutation = ( queryClient: QueryClient, - options: MutationOptions, -): Promise => { - return queryClient.getMutationCache().build(queryClient, options).execute() + options: MutationOptions, + variables: TVariables, +) => { + return queryClient + .getMutationCache() + .build(queryClient, options) + .execute(variables) } // This monkey-patches the isServer-value from utils, diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 0b981c597a2..11d4300139c 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -247,7 +247,7 @@ export interface QueryObserverOptions< */ select?: (data: TQueryData) => TData /** - * If set to `true`, the query will suspend when `status === 'loading'` + * If set to `true`, the query will suspend when `status === 'pending'` * and throw errors when `status === 'error'`. * Defaults to `false`. */ @@ -569,7 +569,6 @@ export interface MutationOptions< > { mutationFn?: MutationFunction mutationKey?: MutationKey - variables?: TVariables onMutate?: ( variables: TVariables, ) => Promise | TContext | undefined @@ -657,6 +656,7 @@ export interface MutationObserverIdleResult< TContext = unknown, > extends MutationObserverBaseResult { data: undefined + variables: undefined error: null isError: false isIdle: true @@ -672,6 +672,7 @@ export interface MutationObserverLoadingResult< TContext = unknown, > extends MutationObserverBaseResult { data: undefined + variables: TVariables error: null isError: false isIdle: false @@ -688,6 +689,7 @@ export interface MutationObserverErrorResult< > extends MutationObserverBaseResult { data: undefined error: TError + variables: TVariables isError: true isIdle: false isPending: false @@ -703,6 +705,7 @@ export interface MutationObserverSuccessResult< > extends MutationObserverBaseResult { data: TData error: null + variables: TVariables isError: false isIdle: false isPending: false diff --git a/packages/query-core/src/utils.ts b/packages/query-core/src/utils.ts index 63fc3b6fd55..33a212ee55d 100644 --- a/packages/query-core/src/utils.ts +++ b/packages/query-core/src/utils.ts @@ -1,6 +1,12 @@ import type { Mutation } from './mutation' import type { Query } from './query' -import type { FetchStatus, MutationKey, QueryKey, QueryOptions } from './types' +import type { + FetchStatus, + MutationKey, + MutationStatus, + QueryKey, + QueryOptions, +} from './types' // TYPES @@ -45,9 +51,9 @@ export interface MutationFilters { */ mutationKey?: MutationKey /** - * Include or exclude fetching mutations + * Filter by mutation status */ - fetching?: boolean + status?: MutationStatus } export type DataUpdateFunction = (input: TInput) => TOutput @@ -138,7 +144,7 @@ export function matchMutation( filters: MutationFilters, mutation: Mutation, ): boolean { - const { exact, fetching, predicate, mutationKey } = filters + const { exact, status, predicate, mutationKey } = filters if (mutationKey) { if (!mutation.options.mutationKey) { return false @@ -152,10 +158,7 @@ export function matchMutation( } } - if ( - typeof fetching === 'boolean' && - (mutation.state.status === 'pending') !== fetching - ) { + if (status && mutation.state.status !== status) { return false } diff --git a/packages/query-persist-client-core/src/__tests__/persist.test.ts b/packages/query-persist-client-core/src/__tests__/persist.test.ts index 5bfe4cccbf5..1e25233c07d 100644 --- a/packages/query-persist-client-core/src/__tests__/persist.test.ts +++ b/packages/query-persist-client-core/src/__tests__/persist.test.ts @@ -20,7 +20,6 @@ describe('persistQueryClientSubscribe', () => { queryClient.getMutationCache().build(queryClient, { mutationFn: async (text: string) => text, - variables: 'todo', }) const result = await persister.restoreClient() diff --git a/packages/react-query/src/__tests__/suspense.test.tsx b/packages/react-query/src/__tests__/suspense.test.tsx index a83d5537b12..8240454ad11 100644 --- a/packages/react-query/src/__tests__/suspense.test.tsx +++ b/packages/react-query/src/__tests__/suspense.test.tsx @@ -1118,7 +1118,7 @@ describe('useQueries with suspense', () => { await sleep(200) return '2' }, - staleTime: 1000, + staleTime: 2000, suspense: false, }, ], diff --git a/packages/react-query/src/__tests__/useMutation.test.tsx b/packages/react-query/src/__tests__/useMutation.test.tsx index 412227afb90..1f43a5c8d6c 100644 --- a/packages/react-query/src/__tests__/useMutation.test.tsx +++ b/packages/react-query/src/__tests__/useMutation.test.tsx @@ -927,10 +927,11 @@ describe('useMutation', () => { function Page() { const mutation = useMutation({ - mutationFn: async (_text: string) => { + mutationFn: async (text: string) => { count++ + const result = `result-${text}` await sleep(10) - return `result${count}` + return result }, onSuccess, onSettled, @@ -940,13 +941,23 @@ describe('useMutation', () => {
    +
    data: {mutation.data ?? 'null'}, status: {mutation.status} @@ -959,22 +970,38 @@ describe('useMutation', () => { await rendered.findByText('data: null, status: idle') - fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) - fireEvent.click(rendered.getByRole('button', { name: /mutate/i })) + fireEvent.click(rendered.getByRole('button', { name: /mutate1/i })) + fireEvent.click(rendered.getByRole('button', { name: /mutate2/i })) - await rendered.findByText('data: result2, status: success') + await rendered.findByText('data: result-todo2, status: success') expect(count).toBe(2) expect(onSuccess).toHaveBeenCalledTimes(2) + expect(onSuccess).toHaveBeenNthCalledWith( + 1, + 'result-todo1', + 'todo1', + undefined, + ) + expect(onSuccess).toHaveBeenNthCalledWith( + 2, + 'result-todo2', + 'todo2', + undefined, + ) expect(onSettled).toHaveBeenCalledTimes(2) expect(onSuccessMutate).toHaveBeenCalledTimes(1) - expect(onSuccessMutate).toHaveBeenCalledWith('result2', 'todo', undefined) + expect(onSuccessMutate).toHaveBeenCalledWith( + 'result-todo2', + 'todo2', + undefined, + ) expect(onSettledMutate).toHaveBeenCalledTimes(1) expect(onSettledMutate).toHaveBeenCalledWith( - 'result2', + 'result-todo2', null, - 'todo', + 'todo2', undefined, ) }) diff --git a/packages/react-query/src/__tests__/useIsMutating.test.tsx b/packages/react-query/src/__tests__/useMutationState.test.tsx similarity index 78% rename from packages/react-query/src/__tests__/useIsMutating.test.tsx rename to packages/react-query/src/__tests__/useMutationState.test.tsx index 6048eeaf44a..ebc71ab4fab 100644 --- a/packages/react-query/src/__tests__/useIsMutating.test.tsx +++ b/packages/react-query/src/__tests__/useMutationState.test.tsx @@ -1,6 +1,6 @@ import { fireEvent, render, waitFor } from '@testing-library/react' import * as React from 'react' -import { useIsMutating } from '../useIsMutating' +import { useIsMutating, useMutationState } from '../useMutationState' import { useMutation } from '../useMutation' import { createQueryClient, @@ -9,6 +9,7 @@ import { sleep, } from './utils' import * as MutationCacheModule from '../../../query-core/src/mutationCache' +import { screen } from 'solid-testing-library' describe('useIsMutating', () => { it('should return the number of fetching mutations', async () => { @@ -95,7 +96,7 @@ describe('useIsMutating', () => { } renderWithClient(queryClient, ) - await waitFor(() => expect(isMutatings).toEqual([0, 1, 1, 0])) + await waitFor(() => expect(isMutatings).toEqual([0, 1, 0])) }) it('should filter correctly by predicate', async () => { @@ -136,7 +137,7 @@ describe('useIsMutating', () => { } renderWithClient(queryClient, ) - await waitFor(() => expect(isMutatings).toEqual([0, 1, 1, 0])) + await waitFor(() => expect(isMutatings).toEqual([0, 1, 0])) }) it('should not change state if unmounted', async () => { @@ -226,3 +227,58 @@ describe('useIsMutating', () => { await waitFor(() => rendered.getByText('mutating: 1')) }) }) + +describe('useMutationState', () => { + it('should return variables after calling mutate', async () => { + const queryClient = createQueryClient() + const variables: unknown[][] = [] + const mutationKey = ['mutation'] + + function Variables() { + variables.push( + useMutationState({ + filters: { mutationKey, status: 'pending' }, + select: (mutation) => mutation.state.variables, + }), + ) + + return null + } + + function Mutate() { + const { mutate, data } = useMutation({ + mutationKey, + mutationFn: async (input: number) => { + await sleep(150) + return 'data' + input + }, + }) + + return ( +
    + data: {data ?? 'null'} + +
    + ) + } + + function Page() { + return ( +
    + + +
    + ) + } + + const rendered = renderWithClient(queryClient, ) + + await waitFor(() => rendered.getByText('data: null')) + + fireEvent.click(screen.getByRole('button', { name: /mutate/i })) + + await waitFor(() => rendered.getByText('data: data1')) + + expect(variables).toEqual([[], [1], []]) + }) +}) diff --git a/packages/react-query/src/__tests__/utils.tsx b/packages/react-query/src/__tests__/utils.tsx index a0f66ca852a..3f4c66241dd 100644 --- a/packages/react-query/src/__tests__/utils.tsx +++ b/packages/react-query/src/__tests__/utils.tsx @@ -1,6 +1,6 @@ import * as React from 'react' import { act, render } from '@testing-library/react' -import type { QueryClientConfig, MutationOptions } from '..' +import type { QueryClientConfig } from '..' import { QueryClient, QueryClientProvider } from '..' import * as utils from '@tanstack/query-core' @@ -86,13 +86,6 @@ export function expectTypeNotAny(_: 0 extends 1 & T ? never : T): void { return undefined } -export function executeMutation( - queryClient: QueryClient, - options: MutationOptions, -): Promise { - return queryClient.getMutationCache().build(queryClient, options).execute() -} - // This monkey-patches the isServer-value from utils, // so that we can pretend to be in a server environment export function setIsServer(isServer: boolean) { diff --git a/packages/react-query/src/index.ts b/packages/react-query/src/index.ts index 4b0f484a9f6..b4e09103441 100644 --- a/packages/react-query/src/index.ts +++ b/packages/react-query/src/index.ts @@ -22,7 +22,7 @@ export { useQueryErrorResetBoundary, } from './QueryErrorResetBoundary' export { useIsFetching } from './useIsFetching' -export { useIsMutating } from './useIsMutating' +export { useIsMutating, useMutationState } from './useMutationState' export { useMutation } from './useMutation' export { useInfiniteQuery } from './useInfiniteQuery' export { useIsRestoring, IsRestoringProvider } from './isRestoring' diff --git a/packages/react-query/src/useIsMutating.ts b/packages/react-query/src/useIsMutating.ts deleted file mode 100644 index d4624d7d375..00000000000 --- a/packages/react-query/src/useIsMutating.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as React from 'react' - -import type { MutationFilters, QueryClient } from '@tanstack/query-core' -import { notifyManager } from '@tanstack/query-core' -import { useQueryClient } from './QueryClientProvider' - -export function useIsMutating( - filters?: MutationFilters, - queryClient?: QueryClient, -): number { - const client = useQueryClient(queryClient) - const mutationCache = client.getMutationCache() - - return React.useSyncExternalStore( - React.useCallback( - (onStoreChange) => - mutationCache.subscribe(notifyManager.batchCalls(onStoreChange)), - [mutationCache], - ), - () => client.isMutating(filters), - () => client.isMutating(filters), - ) -} diff --git a/packages/react-query/src/useMutationState.ts b/packages/react-query/src/useMutationState.ts new file mode 100644 index 00000000000..a5d53fa64d6 --- /dev/null +++ b/packages/react-query/src/useMutationState.ts @@ -0,0 +1,81 @@ +import * as React from 'react' + +import type { + MutationFilters, + QueryClient, + Mutation, + MutationCache, + RegisteredError, +} from '@tanstack/query-core' +import { notifyManager, replaceEqualDeep } from '@tanstack/query-core' +import { useQueryClient } from './QueryClientProvider' +import type { MutationState } from '@tanstack/query-core/build/lib/mutation' + +export function useIsMutating( + filters?: MutationFilters, + queryClient?: QueryClient, +): number { + const client = useQueryClient(queryClient) + return useMutationState( + { filters: { ...filters, status: 'pending' } }, + client, + ).length +} + +type MutationStateOptions = { + filters?: MutationFilters + select?: ( + mutation: Mutation, + ) => TResult +} + +function getResult( + mutationCache: MutationCache, + options: MutationStateOptions, +): Array { + return mutationCache + .findAll(options.filters) + .map( + (mutation): TResult => + (options.select + ? options.select( + mutation as Mutation, + ) + : mutation.state) as TResult, + ) +} + +export function useMutationState( + options: MutationStateOptions = {}, + queryClient?: QueryClient, +): Array { + const mutationCache = useQueryClient(queryClient).getMutationCache() + const optionsRef = React.useRef(options) + const result = React.useRef>() + if (!result.current) { + result.current = getResult(mutationCache, options) + } + + React.useEffect(() => { + optionsRef.current = options + }) + + return React.useSyncExternalStore( + React.useCallback( + (onStoreChange) => + mutationCache.subscribe(() => { + const nextResult = replaceEqualDeep( + result.current, + getResult(mutationCache, optionsRef.current), + ) + if (result.current !== nextResult) { + result.current = nextResult + notifyManager.schedule(onStoreChange) + } + }), + [mutationCache], + ), + () => result.current, + () => result.current, + )! +} diff --git a/packages/solid-query/src/__tests__/createQuery.test.tsx b/packages/solid-query/src/__tests__/createQuery.test.tsx index 2bf503784bb..b39fdab66fa 100644 --- a/packages/solid-query/src/__tests__/createQuery.test.tsx +++ b/packages/solid-query/src/__tests__/createQuery.test.tsx @@ -1099,7 +1099,10 @@ describe('createQuery', () => { function Page() { const state = createQuery(() => ({ queryKey: key, - queryFn: () => ({ name: 'test' }), + queryFn: async () => { + await sleep(10) + return { name: 'test' } + }, select: (data) => data.name, notifyOnChangeProps: ['data'], })) @@ -1108,14 +1111,12 @@ describe('createQuery', () => { states.push({ ...state }) }) - createEffect(() => { - const refetch = state.refetch - setActTimeout(() => { - refetch() - }, 5) - }) - - return null + return ( +
    + data: {state.data} + +
    + ) } render(() => ( @@ -1124,7 +1125,7 @@ describe('createQuery', () => { )) - await sleep(10) + await waitFor(() => screen.getByText('data: test')) expect(states.length).toBe(2) expect(states[0]).toMatchObject({ data: undefined }) diff --git a/packages/vue-query/src/__tests__/useMutation.types.test.tsx b/packages/vue-query/src/__tests__/useMutation.types.test.tsx index 05617f347a2..6436868c18f 100644 --- a/packages/vue-query/src/__tests__/useMutation.types.test.tsx +++ b/packages/vue-query/src/__tests__/useMutation.types.test.tsx @@ -71,4 +71,31 @@ describe('Discriminated union return type', () => { return }) }) + + it('should narrow variables', () => { + doNotExecute(() => { + const mutation = reactive( + useMutation({ mutationFn: successMutator }), + ) + + if (mutation.isIdle) { + const result: Expect> = true + return result + } + if (mutation.isPending) { + const result: Expect> = true + return result + } + if (mutation.isSuccess) { + const result: Expect> = true + return result + } + if (mutation.isError) { + const result: Expect> = true + return result + } + + return + }) + }) }) diff --git a/packages/vue-query/src/mutationCache.ts b/packages/vue-query/src/mutationCache.ts index 1bd74aa755e..ceffc2d3ce6 100644 --- a/packages/vue-query/src/mutationCache.ts +++ b/packages/vue-query/src/mutationCache.ts @@ -19,7 +19,7 @@ export class MutationCache extends MC { return super.find(cloneDeepUnref(filters)) } - findAll(filters: MaybeRefDeep): Mutation[] { + findAll(filters: MaybeRefDeep = {}): Mutation[] { return super.findAll(cloneDeepUnref(filters)) } }