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

README.md

244 lines6.7 KB

1# @tanstack/offline-transactions
2​
3Offline-first transaction capabilities for TanStack DB that provides durable persistence of mutations with automatic retry when connectivity is restored.
4​
5## Features
6​
7- **Outbox Pattern**: Persist mutations before dispatch for zero data loss
8- **Automatic Retry**: Configurable retry behavior with exponential backoff + jitter by default
9- **Multi-tab Coordination**: Leader election ensures safe storage access
10- **FIFO Sequential Processing**: Transactions execute one at a time in creation order
11- **Flexible Storage**: IndexedDB with localStorage fallback
12- **Type Safe**: Full TypeScript support with TanStack DB integration
13​
14## Installation
15​
16### Web
17​
18```bash
19npm install @tanstack/offline-transactions
20```
21​
22### React Native / Expo
23​
24```bash
25npm install @tanstack/offline-transactions @react-native-community/netinfo
26```
27​
28The React Native implementation requires the `@react-native-community/netinfo` peer dependency for network connectivity detection.
29​
30## Platform Support
31​
32This package provides platform-specific implementations for web and React Native environments:
33​
34- **Web**: Uses browser APIs (`window.online/offline` events, `document.visibilitychange`)
35- **React Native**: Uses React Native primitives (`@react-native-community/netinfo` for network status, `AppState` for foreground/background detection)
36​
37## Quick Start
38​
39Using offline transactions on web and React Native/Expo is identical except for the import. Choose the appropriate import based on your target platform:
40​
41**Web:**
42​
43```typescript
44import { startOfflineExecutor } from '@tanstack/offline-transactions'
45```
46​
47**React Native / Expo:**
48​
49```typescript
50import { startOfflineExecutor } from '@tanstack/offline-transactions/react-native'
51```
52​
53**Usage (same for both platforms):**
54​
55```typescript
56// Setup offline executor
57const offline = startOfflineExecutor({
58 collections: { todos: todoCollection },
59 mutationFns: {
60 syncTodos: async ({ transaction, idempotencyKey }) => {
61 await api.saveBatch(transaction.mutations, { idempotencyKey })
62 },
63 },
64 onLeadershipChange: (isLeader) => {
65 if (!isLeader) {
66 console.warn('Running in online-only mode (another tab is the leader)')
67 }
68 },
69})
70​
71// Create offline transactions
72const offlineTx = offline.createOfflineTransaction({
73 mutationFnName: 'syncTodos',
74 autoCommit: false,
75})
76​
77offlineTx.mutate(() => {
78 todoCollection.insert({
79 id: crypto.randomUUID(),
80 text: 'Buy milk',
81 completed: false,
82 })
83})
84​
85// Execute with automatic offline support
86await offlineTx.commit()
87```
88​
89## Core Concepts
90​
91### Outbox-First Persistence
92​
93Mutations are persisted to a durable outbox before being applied, ensuring zero data loss during offline periods:
94​
951. Mutation is persisted to IndexedDB/localStorage
962. Optimistic update is applied locally
973. When online, mutation is sent to server
984. On success, mutation is removed from outbox
99​
100### Multi-tab Coordination
101​
102Only one tab acts as the "leader" to safely manage the outbox:
103​
104- **Leader tab**: Full offline support with outbox persistence
105- **Non-leader tabs**: Online-only mode for safety
106- **Leadership transfer**: Automatic failover when leader tab closes
107​
108### FIFO Sequential Processing
109​
110Transactions are processed one at a time in the order they were created:
111​
112- **Sequential execution**: All transactions execute in FIFO order
113- **Dependency safety**: Avoids conflicts between transactions that may reference each other
114- **Predictable behavior**: Transactions complete in the exact order they were created
115​
116## API Reference
117​
118### startOfflineExecutor(config)
119​
120Creates and starts an offline executor instance.
121​
122```typescript
123interface OfflineConfig {
124 collections: Record<string, Collection>
125 mutationFns: Record<string, MutationFn>
126 storage?: StorageAdapter
127 maxConcurrency?: number
128 jitter?: boolean
129 beforeRetry?: (transactions: OfflineTransaction[]) => OfflineTransaction[]
130 onUnknownMutationFn?: (name: string, tx: OfflineTransaction) => void
131 onLeadershipChange?: (isLeader: boolean) => void
132 onlineDetector?: OnlineDetector
134```
135​
136### OfflineExecutor
137​
138#### Properties
139​
140- `isOfflineEnabled: boolean` - Whether this tab can persist offline transactions
141​
142#### Methods
143​
144- `createOfflineTransaction(options)` - Create a manual offline transaction
145- `waitForTransactionCompletion(id)` - Wait for a specific transaction to complete
146- `removeFromOutbox(id)` - Manually remove transaction from outbox
147- `peekOutbox()` - View all pending transactions
148- `dispose()` - Clean up resources
149​
150### Error Handling
151​
152Use `NonRetriableError` for permanent failures:
153​
154```typescript
155import { NonRetriableError } from '@tanstack/offline-transactions'
156​
157const mutationFn = async ({ transaction }) => {
158 try {
159 await api.save(transaction.mutations)
160 } catch (error) {
161 if (error.status === 422) {
162 throw new NonRetriableError('Invalid data - will not retry')
163 }
164 throw error // Will retry with backoff
165 }
167```
168​
169## Advanced Usage
170​
171### Custom Storage Adapter
172​
173```typescript
174import {
175 IndexedDBAdapter,
176 LocalStorageAdapter,
177} from '@tanstack/offline-transactions'
178​
179const executor = startOfflineExecutor({
180 // Use custom storage
181 storage: new IndexedDBAdapter('my-app', 'transactions'),
182 // ... other config
183})
184```
185​
186### Manual Transaction Control
187​
188```typescript
189const tx = executor.createOfflineTransaction({
190 mutationFnName: 'syncData',
191 autoCommit: false,
192})
193​
194tx.mutate(() => {
195 collection.insert({ id: '1', text: 'Item 1' })
196 collection.insert({ id: '2', text: 'Item 2' })
197})
198​
199// Commit when ready
200await tx.commit()
201```
202​
203## Migration from TanStack DB
204​
205This package uses explicit offline transactions to provide offline capabilities:
206​
207```typescript
208// Before: Standard TanStack DB (online only)
209todoCollection.insert({ id: '1', text: 'Buy milk' })
210​
211// After: Explicit offline transactions
212const offline = startOfflineExecutor({
213 collections: { todos: todoCollection },
214 mutationFns: {
215 syncTodos: async ({ transaction }) => {
216 await api.sync(transaction.mutations)
217 },
218 },
219})
220​
221const tx = offline.createOfflineTransaction({ mutationFnName: 'syncTodos' })
222tx.mutate(() => todoCollection.insert({ id: '1', text: 'Buy milk' }))
223await tx.commit() // Works offline!
224```
225​
226## Platform Support
227​
228### Web Browsers
229​
230- **IndexedDB**: Modern browsers (primary storage)
231- **localStorage**: Fallback for limited environments
232- **Web Locks API**: Chrome 69+, Firefox 96+ (preferred leader election)
233- **BroadcastChannel**: All modern browsers (fallback leader election)
234​
235### React Native
236​
237- **React Native**: 0.60+ (tested with latest versions)
238- **Expo**: SDK 40+ (tested with latest versions)
239- **Required peer dependency**: `@react-native-community/netinfo` for network connectivity detection
240- **Storage**: Uses AsyncStorage or custom storage adapters
241​
242## License
243​
244MIT