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

createPacedMutations.md

96 lines2.2 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:93](https://github.com/TanStack/db/blob/main/packages/db/src/paced-mutations.ts#L93)
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.
22​
23## Type Parameters
24​
25### TVariables
26​
27`TVariables` = `unknown`
28​
29### T
30​
31`T` *extends* `object` = `Record`\<`string`, `unknown`\>
32​
33## Parameters
34​
35### config
36​
37[`PacedMutationsConfig`](../interfaces/PacedMutationsConfig.md)\<`TVariables`, `T`\>
38​
39Configuration including onMutate, mutationFn and strategy
40​
41## Returns
42​
43A function that accepts variables and returns a Transaction
44​
45```ts
46(variables): Transaction<T>;
47```
48​
49### Parameters
50​
51#### variables
52​
53`TVariables`
54​
55### Returns
56​
57[`Transaction`](../interfaces/Transaction.md)\<`T`\>
58​
59## Examples
60​
61```ts
62// Debounced mutations for auto-save
63const updateTodo = createPacedMutations<string>({
64 onMutate: (text) => {
65 // Apply optimistic update immediately
66 collection.update(id, draft => { draft.text = text })
67 },
68 mutationFn: async ({ transaction }) => {
69 await api.save(transaction.mutations)
70 },
71 strategy: debounceStrategy({ wait: 500 })
72})
73​
74// Call with variables, returns a transaction
75const tx = updateTodo('New text')
76​
77// Await persistence or handle errors
78await tx.isPersisted.promise
79```
80​
81```ts
82// Queue strategy for sequential processing
83const addTodo = createPacedMutations<{ text: string }>({
84 onMutate: ({ text }) => {
85 collection.insert({ id: uuid(), text, completed: false })
86 },
87 mutationFn: async ({ transaction }) => {
88 await api.save(transaction.mutations)
89 },
90 strategy: queueStrategy({
91 wait: 200,
92 addItemsTo: 'back',
93 getItemsFrom: 'front'
94 })
95})
96```