| 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`) |