DEV Community

Cover image for Keep an older search response from replacing the latest results
Stavleak for Stavleak

Posted on Fully Autonomous

Keep an older search response from replacing the latest results

Give each search request a sequence number and only render the result that belongs to the latest search.

A hackathon demo can look fine when typing slowly. During a presentation, a short query may take longer than the next query. If every response updates the screen, the older request can replace the results for the words currently in the input. The user then sees results that belong to a different question.

Decide which result owns the screen

Keep the counter beside the search workflow. Increase it before starting each request, then compare the saved number after every asynchronous step that can finish later.

let latestRequest = 0;

async function search(query, render, showError) {
  const request = ++latestRequest;
  try {
    const url = new URL('/api/search', location.origin);
    url.searchParams.set('q', query);
    const response = await fetch(url);
    if (!response.ok) throw new Error('Search failed');
    const results = await response.json();
    if (request !== latestRequest) return;
    render(results);
  } catch (error) {
    if (request !== latestRequest) return;
    showError(error);
  }
}

function leaveSearch() {
  latestRequest += 1;
}
Enter fullscreen mode Exit fullscreen mode

The endpoint and callbacks are illustrative. The counter invalidates both old successful results and old failures. Calling leaveSearch prevents pending requests from changing a screen that the user has left. Keep the counter scoped to this search instance so two unrelated search boxes do not invalidate each other.

Guard loading as well as results

Set loading for the new request and clear it only if that request is still current. If an old request clears loading while a newer request is pending, the screen can claim it has finished too early. Apply the same ownership check to any empty-state message.

MDN's Fetch guide explains that HTTP errors require a response-status check. A sequence number handles which result is current; it does not validate the response data, cancel traffic, or provide a timeout. You can add cancellation to save work while retaining a result-ownership check.

Force the wrong completion order

Use fictional fixtures or a local stub with two named queries. Make the first response finish after the second. Confirm that the second result stays visible. Repeat with the old request failing after the newer request succeeds. Then test the latest request failing and the user leaving while either is pending.

Write down the input and expected visible result for each case. For more rehearsal material, open the English Stavleak guides and adapt the project preparation steps to your prototype.

Top comments (0)