Implement optimisticUpdate(store, mutate, fetch)
The pattern behind every "the UI updates instantly, before the server confirms" interaction. This is the data-layer mechanics only, no React involved. Write optimisticUpdate(store, mutate, fetch) where store is a plain mutable object:
- Apply
mutate(store)immediately, synchronously, before awaiting anything. - Call
await fetch()to persist the change. - If
fetch()resolves, keep the optimistic state as-is. - If
fetch()rejects, rollstoreback to exactly what it was before step 1, then re-throw the error.
const store = { count: 0 };
await optimisticUpdate(store, (s) => { s.count += 1; }, () => api.increment());
// store.count is 1 immediately; rolled back to 0 if api.increment() rejects