Sobes.tech
Middle

What will happen if a user quickly switches between tabs (movies/series), each making an API request? How to fix this?

sobes.tech AI

Answer from AI

If a user quickly switches between tabs (for example, "movies" and "series"), and each tab triggers an API request, there may be a situation where responses arrive out of order, not matching the sequence of requests made. As a result, the UI might display data from the tab that is not currently active.

Problems:

  • Switching causes multiple parallel requests.
  • Responses arrive asynchronously and may update the state after switching.

How to fix:

  1. Cancel previous requests — when switching tabs, cancel all unfinished requests so their results are not applied.

  2. Use tokens or request counters — generate a unique identifier for each request, and update the state only if the response matches the latest request.

  3. Debounce switching — delay sending the request to avoid unnecessary calls during rapid switching.

Example in JavaScript using AbortController to cancel requests:

let currentController = null;

function fetchDataForTab(tab) {
  if (currentController) {
    currentController.abort(); // cancel previous request
  }
  currentController = new AbortController();
  fetch(`/api/${tab}`, { signal: currentController.signal })
    .then(response => response.json())
    .then(data => {
      // update UI only if the request was not canceled
      renderData(tab, data);
    })
    .catch(err => {
      if (err.name === 'AbortError') {
        // request was canceled, do nothing
      } else {
        console.error(err);
      }
    });
}
What will happen if a user quickly switches between… - sobes.tech