Invental/Review lessons/Check, then act on stale state

Check, then act on stale state

Pin the target before the first await

In a loop that awaits network calls, any reactive “current” value can change between iterations. Capture the target before the first await and pass it down, or the user's navigation will redirect your writes.

01 · Before and afterThe pattern

TypeScript
// before: reads whatever agent is open *now*, after each await
for (const batch of batches) await apply(currentAgent(), batch);

// after: pin the target once, and tell "nothing to do" apart from "failed"
const target = currentAgent();
for (const batch of batches) {
  const r = await apply(target, batch);   // { ok: true, value } | { ok: false }
  if (!r.ok) break;                       // a no-op keeps going
}

02 · Run it on your appThe check

If a user switches pages while a multi-step save is running, does every remaining step still write to the record they started on?

If the honest answer is no or not sure, this is worth a look before it reaches production.

Want this checked on your code?

Tell us what you are building and what worries you. We match a senior reviewer to your code and confirm scope before anything starts.

— Get in touch
hi@invental.co ↗
— Or
— What to include

A link or short description of the code or system, what you want checked, your stack, and when you need the answer. No repository access is needed until scope is agreed.

— Or leave a note
We reply within one business day.