Open History to see the last commit
1import { useEffect, useMemo, useState } from 'react'
2import mitt from 'mitt'
3import {
4 createCollection,
5 debounceStrategy,
6 queueStrategy,
7 throttleStrategy,
8 usePacedMutations,
9} from '@tanstack/react-db'
10import type { PendingMutation, Transaction } from '@tanstack/react-db'
11
12interface Item {
13 id: number
14 value: number
15 timestamp: number
16}
17
18// Create event emitter for fake server communication
19const serverEmitter = mitt()
20
21// Fake server store - initialize with a single item
22const fakeServer = new Map<number, Item>([
23 [1, { id: 1, value: 0, timestamp: Date.now() }],
24])
25
26// Create a collection with fake sync
27const itemCollection = createCollection<Item>({
28 id: `items`,
29 getKey: (item) => item.id,
30 startSync: true,
31 sync: {
32 sync: ({ begin, write, commit, markReady }) => {
33 // Initial sync - load the initial item from fake server
34 begin()
35 fakeServer.forEach((item) => {
36 write({
37 type: `insert`,
38 value: item,
39 })
40 })
41 commit()
42 markReady()
43
44 // Listen for server updates and sync them back
45 // @ts-expect-error mitt typing
46 serverEmitter.on(`*`, (_, changes: Array<PendingMutation<Item>>) => {
47 begin()
48 changes.forEach((change) => {
49 if (change.type === `update`) {
50 write({
51 type: change.type,
52 // @ts-expect-error pending mutation type
53 value: change.modified,
54 })
55 } else {
56 write({
57 type: change.type,
58 // @ts-expect-error pending mutation type
59 value: change.changes,
60 })
61 }
62 })
63 commit()
64 })
65 },
66 },
67})
68
69// Track transaction state for visualization
70interface TrackedTransaction {
71 id: string
72 transaction: Transaction
73 state: `pending` | `executing` | `completed` | `failed`
74 mutations: Array<PendingMutation<Item>>
75 createdAt: number
76 executingAt?: number
77 completedAt?: number
78}
79
80type StrategyType = `debounce` | `queue` | `throttle`
81
82export function App() {
83 const [strategyType, setStrategyType] = useState<StrategyType>(`debounce`)
84 const [wait, setWait] = useState(300)
85 const [leading, setLeading] = useState(false)
86 const [trailing, setTrailing] = useState(true)
87
88 const [transactions, setTransactions] = useState<Array<TrackedTransaction>>(
89 [],
90 )
91 const [optimisticState, setOptimisticState] = useState<Item | null>(null)
92 const [syncedState, setSyncedState] = useState<Item>(fakeServer.get(1)!)
93
94 // Initialize optimistic state from collection when ready
95 useEffect(() => {
96 itemCollection.stateWhenReady().then(() => {
97 setOptimisticState(itemCollection.get(1))
98 })
99 }, [])
100
101 // Create the strategy based on current settings
102 // Memoize to prevent recreation on every render
103 const strategy = useMemo(() => {
104 if (strategyType === `debounce`) {
105 return debounceStrategy({ wait, leading, trailing })
106 } else if (strategyType === `queue`) {
107 return queueStrategy({ wait })
108 } else {
109 return throttleStrategy({ wait, leading, trailing })
110 }
111 }, [strategyType, wait, leading, trailing])
112
113 // Create the paced mutations hook with onMutate for optimistic updates
114 const mutate = usePacedMutations<number>({
115 onMutate: (newValue) => {
116 // Apply optimistic update immediately
117 itemCollection.update(1, (draft) => {
118 draft.value = newValue
119 draft.timestamp = Date.now()
120 })
121 },
122 mutationFn: async ({ transaction }) => {
123 console.log(`mutationFn called with transaction:`, transaction)
124
125 // Update transaction state to executing when commit starts
126 const executingAt = Date.now()
127 setTransactions((prev) =>
128 prev.map((t) => {
129 if (t.id === transaction.id) {
130 return { ...t, state: `executing` as const, executingAt }
131 }
132 return t
133 }),
134 )
135
136 // Simulate network delay to fake server (random 100-600ms)
137 const delay = Math.random() * 500 + 100
138 await new Promise((resolve) => setTimeout(resolve, delay))
139
140 // Write mutations to fake server
141 transaction.mutations.forEach((mutation) => {
142 console.log(`Processing mutation:`, mutation)
143 if (mutation.type === `insert`) {
144 const item = mutation.changes as Item
145 fakeServer.set(item.id, item)
146 } else if (mutation.type === `update`) {
147 const item = mutation.modified as Item
148 fakeServer.set(item.id, item)
149 } else {
150 // delete
151 fakeServer.delete(mutation.key as number)
152 }
153 })
154
155 // Update synced state
156 setSyncedState(fakeServer.get(1)!)
157
158 console.log(`Emitting sync event`)
159 // Sync back from server
160 serverEmitter.emit(`sync`, transaction.mutations)
161 },
162 strategy,
163 })
164
165 // Trigger a mutation with a specific value
166 const triggerMutation = (newValue: number) => {
167 // Pass the value directly - onMutate will apply the optimistic update
168 const tx = mutate(newValue)
169
170 // Update optimistic state after onMutate has been called
171 setOptimisticState(itemCollection.get(1))
172
173 // Track this transaction
174 const tracked: TrackedTransaction = {
175 id: tx.id,
176 transaction: tx,
177 state: `pending`,
178 mutations: tx.mutations,
179 createdAt: Date.now(),
180 }
181
182 setTransactions((prev) => {
183 // Only add if this transaction ID isn't already tracked
184 if (prev.some((t) => t.id === tx.id)) {
185 return prev
186 }
187 return [...prev, tracked]
188 })
189
190 // Listen for completion
191 tx.isPersisted.promise
192 .then(() => {
193 setTransactions((prev) =>
194 prev.map((t) => {
195 if (t.id === tx.id) {
196 return {
197 ...t,
198 state: `completed` as const,
199 completedAt: Date.now(),
200 }
201 }
202 return t
203 }),
204 )
205 // Update optimistic state after completion
206 setOptimisticState(itemCollection.get(1))
207 })
208 .catch((error) => {
209 console.error(`Transaction failed:`, error)
210 setTransactions((prev) =>
211 prev.map((t) => {
212 if (t.id === tx.id) {
213 return { ...t, state: `failed` as const, completedAt: Date.now() }
214 }
215 return t
216 }),
217 )
218 // Update optimistic state after failure
219 setOptimisticState(itemCollection.get(1))
220 })
221 }
222
223 const pending = transactions.filter((t) => t.state === `pending`)
224 const executing = transactions.filter((t) => t.state === `executing`)
225 const completed = transactions.filter((t) => t.state === `completed`)
226
227 return (
228 <div className="app">
229 <h1>Paced Mutations Demo</h1>
230 <p className="subtitle">
231 Drag the slider to trigger mutations and see how different strategies
232 batch, queue, and persist changes
233 </p>
234
235 <div className="stats">
236 <div className="stat-card">
237 <div className="stat-value">{optimisticState?.value ?? 0}</div>
238 <div className="stat-label">Optimistic Value</div>
239 </div>
240 <div className="stat-card">
241 <div className="stat-value">{syncedState.value}</div>
242 <div className="stat-label">Synced Value</div>
243 </div>
244 </div>
245
246 <div className="stats">
247 <div className="stat-card">
248 <div className="stat-value">{pending.length}</div>
249 <div className="stat-label">Pending</div>
250 </div>
251 <div className="stat-card">
252 <div className="stat-value">{executing.length}</div>
253 <div className="stat-label">Executing</div>
254 </div>
255 <div className="stat-card">
256 <div className="stat-value">{completed.length}</div>
257 <div className="stat-label">Completed</div>
258 </div>
259 </div>
260
261 <div className="grid">
262 <div className="panel">
263 <h2>Strategy Configuration</h2>
264
265 <div className="control-group">
266 <label>Strategy Type</label>
267 <select
268 value={strategyType}
269 onChange={(e) => setStrategyType(e.target.value as StrategyType)}
270 >
271 <option value="debounce">Debounce</option>
272 <option value="queue">Queue</option>
273 <option value="throttle">Throttle</option>
274 </select>
275 </div>
276
277 <div className="control-group">
278 <label>Wait Time (ms)</label>
279 <input
280 type="number"
281 value={wait}
282 onChange={(e) => setWait(Number(e.target.value))}
283 min={0}
284 step={100}
285 />
286 </div>
287
288 {(strategyType === `debounce` || strategyType === `throttle`) && (
289 <>
290 <div className="checkbox-group">
291 <input
292 type="checkbox"
293 id="leading"
294 checked={leading}
295 onChange={(e) => setLeading(e.target.checked)}
296 />
297 <label htmlFor="leading">Leading edge execution</label>
298 </div>
299
300 <div className="checkbox-group">
301 <input
302 type="checkbox"
303 id="trailing"
304 checked={trailing}
305 onChange={(e) => setTrailing(e.target.checked)}
306 />
307 <label htmlFor="trailing">Trailing edge execution</label>
308 </div>
309 </>
310 )}
311
312 <div className="control-group">
313 <label>Slider Value: {optimisticState?.value ?? 0}</label>
314 <input
315 type="range"
316 min={0}
317 max={100}
318 value={optimisticState?.value ?? 0}
319 onChange={(e) => triggerMutation(Number(e.target.value))}
320 style={{ width: `100%` }}
321 />
322 <div
323 style={{
324 display: `flex`,
325 justifyContent: `space-between`,
326 fontSize: `12px`,
327 color: `#999`,
328 }}
329 >
330 <span>0</span>
331 <span>50</span>
332 <span>100</span>
333 </div>
334 </div>
335
336 <div style={{ marginTop: `20px`, fontSize: `13px`, color: `#666` }}>
337 <h3 style={{ fontSize: `14px`, marginBottom: `8px` }}>
338 Strategy Info:
339 </h3>
340 {strategyType === `debounce` && (
341 <p>
342 <strong>Debounce:</strong> Waits for {wait}ms of inactivity
343 before persisting.
344 {leading && ` Executes immediately on first call.`}
345 {trailing && ` Executes after wait period.`}
346 </p>
347 )}
348 {strategyType === `queue` && (
349 <p>
350 <strong>Queue:</strong> Processes mutations sequentially in
351 order received (FIFO) with {wait}ms between each.
352 </p>
353 )}
354 {strategyType === `throttle` && (
355 <p>
356 <strong>Throttle:</strong> Ensures at least {wait}ms between
357 executions.
358 {leading && ` Executes immediately on first call.`}
359 {trailing && ` Executes after wait period.`}
360 </p>
361 )}
362 </div>
363 </div>
364
365 <div className="panel">
366 <h2>Transaction Timeline</h2>
367
368 {transactions.length === 0 ? (
369 <div className="empty-state">
370 No mutations yet. Drag the slider to start!
371 </div>
372 ) : (
373 <div className="transaction-list">
374 {[...transactions].reverse().map((tracked) => (
375 <div
376 key={tracked.id}
377 className={`transaction-card ${tracked.state}`}
378 >
379 <div className="transaction-header">
380 <span className="transaction-id">
381 ID: {tracked.id.slice(0, 8)}
382 </span>
383 <span className={`transaction-status ${tracked.state}`}>
384 {tracked.state}
385 </span>
386 </div>
387 <div className="transaction-details">
388 <div>
389 Created:{` `}
390 {new Date(tracked.createdAt).toLocaleTimeString()}
391 </div>
392 {tracked.executingAt && (
393 <div>
394 Started Executing:{` `}
395 {new Date(tracked.executingAt).toLocaleTimeString()}
396 {` `}(pending: {tracked.executingAt - tracked.createdAt}
397 ms)
398 </div>
399 )}
400 {tracked.completedAt && (
401 <div>
402 Completed:{` `}
403 {new Date(tracked.completedAt).toLocaleTimeString()}
404 {tracked.executingAt && (
405 <>
406 {` `}(persisting:{` `}
407 {tracked.completedAt - tracked.executingAt}ms)
408 </>
409 )}
410 </div>
411 )}
412 {tracked.completedAt && (
413 <div style={{ fontWeight: `bold`, marginTop: `4px` }}>
414 Total Duration:{` `}
415 {tracked.completedAt - tracked.createdAt}ms
416 </div>
417 )}
418 </div>
419 <div className="transaction-mutations">
420 <div style={{ fontWeight: `bold`, marginBottom: `4px` }}>
421 Mutations ({tracked.mutations.length}):
422 </div>
423 {tracked.mutations.map((mut, idx) => {
424 if (mut.type === `update`) {
425 const item = mut.modified
426 return (
427 <div key={idx} className="mutation">
428 <span className="mutation-type">{mut.type}</span>
429 <>: value = {item.value}</>
430 </div>
431 )
432 }
433 return (
434 <div key={idx} className="mutation">
435 <span className="mutation-type">{mut.type}</span>
436 </div>
437 )
438 })}
439 </div>
440 </div>
441 ))}
442 </div>
443 )}
444 </div>
445 </div>
446 </div>
447 )
448}