Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

OptimisticUpdate.svelte

38 lines1.1 KB

1<script lang="ts">
2 import { sleep } from '@tanstack/query-test-utils'
3 import { createMutation, setQueryClientContext } from '../../src/index.js'
4 import type { QueryClient } from '@tanstack/query-core'
5​
6 type Props = {
7 queryClient: QueryClient
8 queryKey: Array<string>
9 shouldSucceed: boolean
10 }
11​
12 let { queryClient, queryKey, shouldSucceed }: Props = $props()
13​
14 setQueryClientContext(queryClient)
15​
16 const mutation = createMutation(() => ({
17 mutationFn: (newTodo: string) =>
18 shouldSucceed
19 ? sleep(10).then(() => newTodo)
20 : sleep(10).then(() => Promise.reject(new Error('Some error'))),
21 onMutate: async (newTodo: string) => {
22 await queryClient.cancelQueries({ queryKey })
23 const previousTodos = queryClient.getQueryData<Array<string>>(queryKey)
24​
25 queryClient.setQueryData<Array<string>>(queryKey, (old) => [
26 ...(old ?? []),
27 newTodo,
28 ])
29​
30 return { previousTodos }
31 },
32 onError: (_err, _newTodo, onMutateResult) => {
33 queryClient.setQueryData(queryKey, onMutateResult?.previousTodos)
34 },
35 }))
36</script>
37​
38<button onclick={() => mutation.mutate('Todo 2')}>add</button>