Skip to content

Commit

Permalink
fix(svelte-5-adapter): function for createMutation options (#7805)
Browse files Browse the repository at this point in the history
* fix(svelte-5-adapter): require function for createMutation options

* Fix type errors
  • Loading branch information
lachlancollins committed Jul 31, 2024
1 parent d2660a5 commit 233666d
Show file tree
Hide file tree
Showing 16 changed files with 46 additions and 35 deletions.
8 changes: 4 additions & 4 deletions examples/svelte/auto-refetching/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@
refetchInterval: intervalMs,
}))
const addMutation = createMutation({
const addMutation = createMutation(() => ({
mutationFn: (value: string) =>
fetch(`${endpoint}?add=${value}`).then((r) => r.json()),
onSuccess: () => client.invalidateQueries({ queryKey: ['refetch'] }),
})
}))
const clearMutation = createMutation({
const clearMutation = createMutation(() => ({
mutationFn: () => fetch(`${endpoint}?clear=1`).then((r) => r.json()),
onSuccess: () => client.invalidateQueries({ queryKey: ['refetch'] }),
})
}))
</script>

<h1>Auto Refetch with stale-time set to 1s</h1>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/optimistic-updates/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
queryFn: fetchTodos,
}))
const addTodoMutation = createMutation({
const addTodoMutation = createMutation(() => ({
mutationFn: createTodo,
onMutate: async (newTodo: string) => {
text = ''
Expand Down Expand Up @@ -74,7 +74,7 @@
onSettled: () => {
client.invalidateQueries({ queryKey: ['optimistic'] })
},
})
}))
</script>

<h1>Optimistic Updates</h1>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/playground/src/routes/AddTodo.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@
})
}
const addMutation = createMutation({
const addMutation = createMutation(() => ({
mutationFn: postTodo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['todos'] })
},
})
}))
</script>

<div>
Expand Down
4 changes: 2 additions & 2 deletions examples/svelte/playground/src/routes/EditTodo.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@
enabled: editingIndex.value !== null,
}))
const saveMutation = createMutation({
const saveMutation = createMutation(() => ({
mutationFn: patchTodo,
onSuccess: (data) => {
// Update `todos` and the individual todo queries when this mutation succeeds
queryClient.invalidateQueries({ queryKey: ['todos'] })
queryClient.setQueryData(['todo', { id: editingIndex }], data)
},
})
}))
const todo = $derived(query.data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@

<div>data: {query.data ?? 'undefined'}</div>
<div>fetchStatus: {query.fetchStatus}</div>
<div>fetched: {fetched}</div>
2 changes: 1 addition & 1 deletion packages/svelte-query/src/createBaseQuery.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function createBaseQuery<

/** Creates a store that has the default options applied */
function updateOptions() {
const queryKey: TQueryKey = $state.snapshot(options().queryKey) as any // remove proxy prevent reactive query in devTools
const queryKey: TQueryKey = $state.snapshot(options().queryKey) as any // remove proxy prevent reactive query in DevTools
const defaultedOptions = client.defaultQueryOptions({
...options(),
queryKey: queryKey,
Expand Down
12 changes: 9 additions & 3 deletions packages/svelte-query/src/createMutation.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
CreateMutateFunction,
CreateMutationOptions,
CreateMutationResult,
FunctionedParams,
} from './types'

import type { DefaultError, QueryClient } from '@tanstack/query-core'
Expand All @@ -16,13 +17,18 @@ export function createMutation<
TVariables = void,
TContext = unknown,
>(
options: CreateMutationOptions<TData, TError, TVariables, TContext>,
options: FunctionedParams<
CreateMutationOptions<TData, TError, TVariables, TContext>
>,
queryClient?: QueryClient,
): CreateMutationResult<TData, TError, TVariables, TContext> {
const client = useQueryClient(queryClient)

const observer = $derived(
new MutationObserver<TData, TError, TVariables, TContext>(client, options),
new MutationObserver<TData, TError, TVariables, TContext>(
client,
options(),
),
)
const mutate = $state<
CreateMutateFunction<TData, TError, TVariables, TContext>
Expand All @@ -31,7 +37,7 @@ export function createMutation<
})

$effect.pre(() => {
observer.setOptions(options)
observer.setOptions(options())
})

const result = $state(observer.getCurrentResult())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
)
$effect(() => {
// @ts-expect-error
states.value = [...untrack(() => states.value), $state.snapshot(query)]
})
</script>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
)
$effect(() => {
// @ts-expect-error
states.value = [...untrack(() => states.value), $state.snapshot(query)]
})
</script>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
const queryClient = new QueryClient()
setQueryClientContext(queryClient)
const mutation = createMutation({ mutationFn: mutationFn })
const mutation = createMutation(() => ({ mutationFn: mutationFn }))
</script>

<button onclick={() => mutation.mutate({ count: ++count })}>Mutate</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,15 @@
const queryClient = new QueryClient()
setQueryClientContext(queryClient)
const mutation = createMutation({
const mutation = createMutation(() => ({
mutationFn: (vars: { count: number }) => Promise.resolve(vars.count),
onSuccess: (data) => {
onSuccessMock(data)
},
onSettled: (data) => {
onSettledMock(data)
},
})
}))
</script>

<button onclick={() => mutation.mutate({ count: ++$count })}>Mutate</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
const queryClient = new QueryClient()
setQueryClientContext(queryClient)
const mutation = createMutation({
const mutation = createMutation(() => ({
mutationFn: () => {
const err = new Error('Expected mock error')
err.stack = ''
return Promise.reject(err)
},
})
}))
</script>

<button onclick={() => mutation.reset()}>Reset</button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
)
$effect(() => {
// @ts-expect-error
states.value = [...untrack(() => states.value), $state.snapshot(query)]
})
</script>
Expand Down
4 changes: 2 additions & 2 deletions packages/svelte-query/tests/useIsMutating/BaseExample.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@
const isMutating = useIsMutating(undefined, queryClient)
const mutation = createMutation(
{
() => ({
mutationKey: ['mutation-1'],
mutationFn: async () => {
await sleep(5)
return 'data'
},
},
}),
queryClient,
)
</script>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { useMutationState } from '../../src/useMutationState.svelte'
import type {
CreateMutationOptions,
FunctionedParams,
MutationStateOptions,
} from '../../src/index'
Expand All @@ -13,8 +14,8 @@
errorMutationOpts,
mutationStateOpts,
}: {
successMutationOpts: CreateMutationOptions
errorMutationOpts: CreateMutationOptions
successMutationOpts: FunctionedParams<CreateMutationOptions>
errorMutationOpts: FunctionedParams<CreateMutationOptions>
mutationStateOpts?: MutationStateOptions | undefined
} = $props()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ describe('useMutationState', () => {

const rendered = render(BaseExample, {
props: {
successMutationOpts: {
successMutationOpts: () => ({
mutationKey: ['success'],
mutationFn: successMutationFn,
},
}),

errorMutationOpts: {
errorMutationOpts: () => ({
mutationKey: ['error'],
mutationFn: errorMutationFn,
},
}),
},
})

Expand Down Expand Up @@ -49,15 +49,15 @@ describe('useMutationState', () => {

const rendered = render(BaseExample, {
props: {
successMutationOpts: {
successMutationOpts: () => ({
mutationKey: ['success'],
mutationFn: successMutationFn,
},
}),

errorMutationOpts: {
errorMutationOpts: () => ({
mutationKey: ['error'],
mutationFn: errorMutationFn,
},
}),

mutationStateOpts: {
filters: { status: 'error' },
Expand Down Expand Up @@ -88,15 +88,15 @@ describe('useMutationState', () => {

const rendered = render(BaseExample, {
props: {
successMutationOpts: {
successMutationOpts: () => ({
mutationKey: ['success'],
mutationFn: successMutationFn,
},
}),

errorMutationOpts: {
errorMutationOpts: () => ({
mutationKey: ['error'],
mutationFn: errorMutationFn,
},
}),

mutationStateOpts: {
filters: { mutationKey: ['success'] },
Expand Down

0 comments on commit 233666d

Please sign in to comment.