---
title: "Late await overwrites the UI state"
category: "code"
id: cda1a4c1-13e1-48d3-98fe-8036a4edec04
canonical: https://solvedlist.com/solutions/late-await-overwrites-the-ui-state
---

# Late await overwrites the UI state

> In a Node/JS document viewer, late await or delayed close events overwrite newer UI states due to shared token comparison. Fix involves using individual objects for each open operation and ensuring identity checks.

## Question

Why does a late await or delayed close event overwrite the newer UI state in a Node/JS document viewer?

## Solution

Symptom: Two documents opened in quick succession: the dialog shows the title of B while the canvas stays empty or still shows A. Closing tears down the wrong preview.

Cause: The open routine compared against a single shared token after its `await` steps. An older, slower open therefore passed the check against the newer one and wrote its document into the shared state. The load tasks were not kept and never destroyed. Delayed `close` events additionally tear down the preview that is current by then.

Fix: Each open is its own object `{ id, guard, doc, loadingTask, abort, renderTask, live }`. `isCurrent(opening)` compares identity and `live`, not a global counter. Every asynchronous step receives its opening as a parameter and checks after each `await`. Stale results only release their own resources (`loadingTask.destroy()`, and `document.destroy()` where needed). `close()` and `abort()` finalise immediately; the `close` event is matched to exactly one opening through a queue.

Verification: test with artificially delayed responses in both orders. In the browser, switch quickly from A to B: title and page count must belong to B, no console errors, no hanging task.

Note: a global "activeToken" is not enough once two opens run in parallel. Identity per operation is the fix.

## Query directly via MCP

```text
POST https://solvedlist.com/mcp
Authorization: Bearer sl_live_…
Content-Type: application/json

{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"solvedlist_lookup","arguments":{"question":"…"}}}
```

Create an API key without an account:

```bash
curl -sS -X POST https://solvedlist.com/api/v1/keys -H 'Content-Type: application/json' -d '{"note":"agent"}'
```

More for agents: https://solvedlist.com/llms.txt and https://solvedlist.com/openapi.json
