Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script lang="ts">
import type { QueryClient, QueryKey } from '@tanstack/query-core'
import { createMutation, setQueryClientContext } from '../../src/index.js'
import { sleep } from '@tanstack/query-test-utils'

type Props = {
queryClient: QueryClient
queryKey: QueryKey
}

const { queryClient, queryKey }: Props = $props()

setQueryClientContext(queryClient)

const mutation = createMutation(() => ({
mutationFn: () => sleep(10).then(() => 'mutated'),
onSuccess: (_data, _variables, _onMutateResult, context) => {
context.client.invalidateQueries({ queryKey })
},
}))
</script>

<button onclick={() => mutation.mutate()}>Mutate</button>
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<script lang="ts">
import type { QueryClient, QueryKey } from '@tanstack/query-core'
import { createMutation, setQueryClientContext } from '../../src/index.js'
import { sleep } from '@tanstack/query-test-utils'

type Props = {
queryClient: QueryClient
queryKey: QueryKey
}

const { queryClient, queryKey }: Props = $props()

setQueryClientContext(queryClient)

const mutation = createMutation(() => ({
mutationFn: (_text: string, context) =>
sleep(10).then(() => context.client.getQueryData(queryKey)),
}))
</script>

<button onclick={() => mutation.mutate('todo')}>Mutate</button>

<div>data: {mutation.data}</div>
24 changes: 24 additions & 0 deletions packages/svelte-query/tests/createMutation/PerCallSuccess.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<script lang="ts">
import type { QueryClient } from '@tanstack/query-core'
import { createMutation, setQueryClientContext } from '../../src/index.js'
import { sleep } from '@tanstack/query-test-utils'

type Props = {
queryClient: QueryClient
perCallOnSuccess: (...args: Array<unknown>) => void
}

const { queryClient, perCallOnSuccess }: Props = $props()

setQueryClientContext(queryClient)

const mutation = createMutation(() => ({
mutationFn: (text: string) => sleep(10).then(() => text),
}))
</script>

<button
onclick={() => mutation.mutate('todo', { onSuccess: perCallOnSuccess })}
>
Mutate
</button>
24 changes: 24 additions & 0 deletions packages/svelte-query/tests/createMutation/SuccessContext.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<script lang="ts">
import type { MutationKey, QueryClient } from '@tanstack/query-core'
import { createMutation, setQueryClientContext } from '../../src/index.js'
import { sleep } from '@tanstack/query-test-utils'

type Props = {
queryClient: QueryClient
mutationKey?: MutationKey
onSuccessMock: (...args: Array<unknown>) => void
}

const { queryClient, mutationKey, onSuccessMock }: Props = $props()

setQueryClientContext(queryClient)

const mutation = createMutation(() => ({
mutationKey,
mutationFn: (text: string) => sleep(10).then(() => text.toUpperCase()),
onMutate: (text: string) => ({ startedWith: text }),
onSuccess: onSuccessMock,
}))
</script>

<button onclick={() => mutation.mutate('todo')}>Mutate</button>
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ import Reset from './Reset.svelte'
import Success from './Success.svelte'
import Failure from './Failure.svelte'
import OptimisticUpdate from './OptimisticUpdate.svelte'
import SuccessContext from './SuccessContext.svelte'
import InvalidateFromContext from './InvalidateFromContext.svelte'
import PerCallSuccess from './PerCallSuccess.svelte'
import MutationFnContext from './MutationFnContext.svelte'

describe('createMutation', () => {
let queryClient: QueryClient
Expand Down Expand Up @@ -171,4 +175,86 @@ describe('createMutation', () => {

expect(queryClient.getQueryData(key)).toEqual(['Todo 1', 'Todo 2'])
})

it('should pass a non-undefined onMutateResult alongside context to onSuccess', async () => {
const onSuccessMock = vi.fn()

const rendered = render(SuccessContext, {
props: { queryClient, onSuccessMock },
})

fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
await vi.advanceTimersByTimeAsync(10)

expect(onSuccessMock).toHaveBeenCalledTimes(1)
const [data, variables, onMutateResult, context] =
onSuccessMock.mock.calls[0]!
expect(data).toBe('TODO')
expect(variables).toBe('todo')
expect(onMutateResult).toEqual({ startedWith: 'todo' })
expect(context.client).toBe(queryClient)
expect(context.meta).toBeUndefined()
expect(context.mutationKey).toBeUndefined()
})

it('should include mutationKey in the context passed to hook-level callbacks', async () => {
const onSuccessMock = vi.fn()

const rendered = render(SuccessContext, {
props: { queryClient, mutationKey: ['todos', 'add'], onSuccessMock },
})

fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
await vi.advanceTimersByTimeAsync(10)

expect(onSuccessMock).toHaveBeenCalledTimes(1)
expect(onSuccessMock.mock.calls[0]?.[3].mutationKey).toEqual([
'todos',
'add',
])
})

it('should give mutationFn the same QueryClient instance via context', async () => {
const key = queryKey()
queryClient.setQueryData(key, 'tag-from-this-client')

const rendered = render(MutationFnContext, {
props: { queryClient, queryKey: key },
})

fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
await vi.advanceTimersByTimeAsync(11)

expect(rendered.getByText('data: tag-from-this-client')).toBeInTheDocument()
})

it('should let onSuccess invalidate queries via context.client without a useQueryClient() closure', async () => {
const key = queryKey()
queryClient.setQueryData(key, 'data')

const rendered = render(InvalidateFromContext, {
props: { queryClient, queryKey: key },
})

expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)

fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
await vi.advanceTimersByTimeAsync(10)

expect(queryClient.getQueryState(key)?.isInvalidated).toBe(true)
})

it('should give a per-call onSuccess the same QueryClient instance via context', async () => {
const perCallOnSuccess = vi.fn()

const rendered = render(PerCallSuccess, {
props: { queryClient, perCallOnSuccess },
})

fireEvent.click(rendered.getByRole('button', { name: /Mutate/i }))
await vi.advanceTimersByTimeAsync(10)

expect(perCallOnSuccess).toHaveBeenCalledTimes(1)
expect(perCallOnSuccess.mock.calls[0]?.[3].client).toBe(queryClient)
})
})
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { describe, expectTypeOf, it } from 'vitest'
import { QueryClient } from '@tanstack/query-core'
import { createMutation } from '../../src/index.js'
import type { DefaultError } from '@tanstack/query-core'
import type {
DefaultError,
MutationFunctionContext,
MutationKey,
} from '@tanstack/query-core'
import type { CreateMutationResult } from '../../src/types.js'

describe('createMutation', () => {
Expand Down Expand Up @@ -144,4 +148,56 @@ describe('createMutation', () => {

expectTypeOf(mutation.data).toEqualTypeOf<string | undefined>()
})

it('should type context as the last argument for mutationFn and every hook-level callback', () => {
createMutation(() => ({
mutationFn: (_vars: string, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
expectTypeOf(context.client).toEqualTypeOf<QueryClient>()
return Promise.resolve('data')
},
onMutate: (_variables, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onError: (_error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSettled: (_data, _error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
}))
})

it('should type context as the last argument for every per-call mutate option', () => {
const mutation = createMutation(() => ({
mutationFn: () => Promise.resolve('data'),
}))

mutation.mutate(undefined, {
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onError: (_error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
onSettled: (_data, _error, _variables, _onMutateResult, context) => {
expectTypeOf(context).toEqualTypeOf<MutationFunctionContext>()
},
})
})

it('should type context.mutationKey as MutationKey', () => {
createMutation(() => ({
mutationKey: ['todos', 'add'] as const,
mutationFn: () => Promise.resolve('data'),
onSuccess: (_data, _variables, _onMutateResult, context) => {
expectTypeOf(context.mutationKey).toEqualTypeOf<
MutationKey | undefined
>()
},
}))
})
})
Loading