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

createPacedMutations.md

99 lines2.5 KB

1---
2id: createPacedMutations
3title: createPacedMutations
4---
5​
6```ts
7function createPacedMutations<TVariables, T>(config): (variables) => Transaction<T>;
8```
9​
10Defined in: [packages/db/src/paced-mutations.ts:99](https://github.com/TanStack/db/blob/main/packages/db/src/paced-mutations.ts#L99)
11​
12Creates a paced mutations manager with pluggable timing strategies.
13​
14This function provides a way to control when and how optimistic mutations
15are persisted to the backend, using strategies like debouncing, queuing,
16or throttling. The optimistic updates are applied immediately via `onMutate`,
17and the actual persistence is controlled by the strategy.
18​
19The returned function accepts variables of type TVariables and returns a
20Transaction object that can be awaited to know when persistence completes
21or to handle errors. The strategy owns `commit()`; calling it on the returned
22transaction throws before persistence starts. `rollback()` remains available.
23If a synchronous `onMutate` calls this manager again and then throws, every
24call merged into that pending transaction rejects together.
25​
26## Type Parameters
27​
28### TVariables
29​
30`TVariables` = `unknown`
31​
32### T
33​
34`T` *extends* `object` = `Record`\<`string`, `unknown`\>
35​
36## Parameters
37​
38### config
39​
40[`PacedMutationsConfig`](../interfaces/PacedMutationsConfig.md)\<`TVariables`, `T`\>
41​
42Configuration including onMutate, mutationFn and strategy
43​
44## Returns
45​
46A function that accepts variables and returns a Transaction
47​
48```ts
49(variables): Transaction<T>;
50```
51​
52### Parameters
53​
54#### variables
55​
56`TVariables`
57​
58### Returns
59​
60[`Transaction`](../interfaces/Transaction.md)\<`T`\>
61​
62## Examples
63​
64```ts
65// Debounced mutations for auto-save
66const updateTodo = createPacedMutations<string>({
67 onMutate: (text) => {
68 // Apply optimistic update immediately
69 collection.update(id, draft => { draft.text = text })
70 },
71 mutationFn: async ({ transaction }) => {
72 await api.save(transaction.mutations)
73 },
74 strategy: debounceStrategy({ wait: 500 })
75})
76​
77// Call with variables, returns a transaction
78const tx = updateTodo('New text')
79​
80// Await persistence or handle errors
81await tx.when('settled')
82```
83​
84```ts
85// Queue strategy for sequential processing
86const addTodo = createPacedMutations<{ text: string }>({
87 onMutate: ({ text }) => {
88 collection.insert({ id: uuid(), text, completed: false })
89 },
90 mutationFn: async ({ transaction }) => {
91 await api.save(transaction.mutations)
92 },
93 strategy: queueStrategy({
94 wait: 200,
95 addItemsTo: 'back',
96 getItemsFrom: 'front'
97 })
98})
99```