BACK
Use casesLast good value — fall back to the previous success
Use cases · 64

Last good value — fall back to the previous success

Pattern

A dashboard refreshes every 30 seconds. If a refresh fails — DON'T show an empty screen. Keep the last known good data, but honestly mark it "stale, last updated 2 minutes ago".

The problem it solves

Imperative code often resets data = null before a refresh, and after a failure the user sees emptiness instead of yesterday's data. Bad UX. On the other hand, hiding the fact that it's stale is also bad.

Operators and why they matter

  • catchError(() => of({type: 'error'})) inside the refresh — a failed request becomes an event, not a stream failure.
  • scan — holds the last successful value between attempts. On success it updates; on error it keeps the old one + marks status=stale.
  • startWith('ok') — the initial refresh.

Gotchas

  • catchError OUTSIDE the trigger stream — the first error stops all future refreshes. The stream dies.
  • Don't hide the stale/error status. The user must know they're seeing old data.
  • For critical data (account balance, medical data), a last good value may be business-unacceptable. Decide per case.

What you get

The UI keeps the last good result but honestly marks it as stale on an error. The user sees data and understands how current it is.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...