Open History to see the last commit
1import { createTransaction } from './transactions'
2import { OnMutateMustBeSynchronousError } from './errors'
3import { isPromiseLike } from './utils/type-guards'
4import type { CreateOptimisticActionsOptions, Transaction } from './types'
5
6/**
7 * Creates an optimistic action function that applies local optimistic updates immediately
8 * before executing the actual mutation on the server.
9 *
10 * This pattern allows for responsive UI updates while the actual mutation is in progress.
11 * The optimistic update is applied via the `onMutate` callback, and the server mutation
12 * is executed via the `mutationFn`.
13 *
14 * **Important:** Inside your `mutationFn`, you must ensure that your server writes have synced back
15 * before you return, as the optimistic state is dropped when you return from the mutation function.
16 * You generally use collection-specific helpers to do this, such as Query's `utils.refetch()`,
17 * direct write APIs, or Electric's `utils.awaitTxId()`.
18 *
19 * @example
20 * ```ts
21 * const addTodo = createOptimisticAction<string>({
22 * onMutate: (text) => {
23 * // Instantly applies local optimistic state
24 * todoCollection.insert({
25 * id: uuid(),
26 * text,
27 * completed: false
28 * })
29 * },
30 * mutationFn: async (text, params) => {
31 * // Persist the todo to your backend
32 * const response = await fetch('/api/todos', {
33 * method: 'POST',
34 * body: JSON.stringify({ text, completed: false }),
35 * })
36 * const result = await response.json()
37 *
38 * // IMPORTANT: Ensure server writes have synced back before returning
39 * // This ensures the optimistic state can be safely discarded
40 * await todoCollection.utils.refetch()
41 *
42 * return result
43 * }
44 * })
45 *
46 * // Usage
47 * const transaction = addTodo('New Todo Item')
48 * ```
49 *
50 * @template TVariables - The type of variables that will be passed to the action function
51 * @param options - Configuration options for the optimistic action
52 * @returns A function that accepts variables of type TVariables and returns a Transaction
53 */
54export function createOptimisticAction<TVariables = unknown>(
55 options: CreateOptimisticActionsOptions<TVariables>,
56) {
57 const { mutationFn, onMutate, ...config } = options
58
59 return (variables: TVariables): Transaction => {
60 // Create transaction with the original config
61 const transaction = createTransaction({
62 ...config,
63 // Wire the mutationFn to use the provided variables
64 mutationFn: async (params) => {
65 return await mutationFn(variables, params)
66 },
67 })
68
69 // Execute the transaction. The mutationFn is called once mutate()
70 // is finished.
71 transaction.mutate(() => {
72 const maybePromise = onMutate(variables) as unknown
73
74 if (isPromiseLike(maybePromise)) {
75 throw new OnMutateMustBeSynchronousError()
76 }
77 })
78
79 return transaction
80 }
81}