Skip to content

Commit eb17766

Browse files
fix(search): ignore stale async search responses
1 parent 66312ae commit eb17766

1 file changed

Lines changed: 7 additions & 0 deletions

File tree

static/js/search.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ import { setWorkspaceMode } from './shared/theme.js';
55

66
// ==================== Search ====================
77

8+
let lastSearchRequestId = 0;
9+
810
export function showSearchPage() {
911
setHamburgerVisible(false);
1012
setWorkspaceMode(false);
@@ -29,6 +31,7 @@ export function showSearchPage() {
2931
}
3032

3133
export async function doSearch() {
34+
const localRequestId = ++lastSearchRequestId;
3235
const input = document.getElementById('search-input');
3336
if (!input) { showSearchPage(); return; }
3437
const query = input.value.trim();
@@ -39,12 +42,15 @@ export async function doSearch() {
3942

4043
try {
4144
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}&limit=50`);
45+
if (localRequestId !== lastSearchRequestId) return;
4246
if (!res.ok) {
4347
let msg = `Search failed (${res.status})`;
4448
try { msg = await res.text() || msg; } catch { /* ignore */ }
49+
if (localRequestId !== lastSearchRequestId) return;
4550
throw new Error(msg);
4651
}
4752
const results = await res.json();
53+
if (localRequestId !== lastSearchRequestId) return;
4854

4955
let html = `<p class="text-muted text-sm">${results.length} result${results.length !== 1 ? 's' : ''}</p><br>`;
5056
html += '<div class="search-results">';
@@ -60,6 +66,7 @@ export async function doSearch() {
6066
html += '</div>';
6167
smoothSet(container, html);
6268
} catch (e) {
69+
if (localRequestId !== lastSearchRequestId) return;
6370
container.innerHTML = `<div class="loading">Error: ${esc(e.message)}</div>`;
6471
}
6572
}

0 commit comments

Comments
 (0)