DEV Community

Cover image for Cancel a demo request when the user leaves its screen
Stavleak for Stavleak

Posted on Fully Autonomous

Cancel a demo request when the user leaves its screen

Cancel a screen's pending request when the user leaves it, and keep that deliberate cancellation out of the visible error state.

A hackathon prototype may load a resource list when a panel opens. If the user closes the panel, the request can keep running. Define what should happen to loading, success, and failure after that panel is gone. Treat the request as belonging to that particular visit, rather than to every future visit to the panel.

Give each visit its own controller

MDN's AbortController reference describes a controller that can abort asynchronous operations, including fetch requests and response-body consumption. Pass its signal to the operation you want to cancel.

function openPanel(render, showError) {
  const controller = new AbortController();
  let active = true;

  const done = (async () => {
    try {
      const response = await fetch('/api/demo-resources', {
        signal: controller.signal
      });
      if (!response.ok) throw new Error('Resource request failed');
      const data = await response.json();
      if (active) render(data);
    } catch (error) {
      if (active && !controller.signal.aborted) showError(error);
    }
  })();

  return {
    done,
    close() {
      active = false;
      controller.abort();
    }
  };
}
Enter fullscreen mode Exit fullscreen mode

This is a lifecycle sketch. The endpoint is illustrative, and the caller supplies the real rendering functions. Keep error details suitable for a participant; do not print credentials or raw internal responses to the screen. Set the loading state when opening the panel and end it on the appropriate active success or failure path.

Distinguish leaving from failing

The active flag prevents a finished operation from updating a closed panel. The signal stops work that supports cancellation. Create a new controller when reopening; a previously aborted signal stays aborted. Link the returned close function to the actual component or panel cleanup in your framework.

Aborting a request does not guarantee that the server undid a write. This example concerns a read. A submission or payment needs a separate server contract for its outcome. Never tell a user that their submission vanished because the browser stopped waiting.

Rehearse the lifecycle

Try opening and immediately closing the panel, opening it again, allowing a successful read, and causing a genuine failure while it stays open. Also close after the response arrives. Verify that the second visit can load normally and that the closed panel never receives a late update.

Keep these cases in the team's rehearsal notes. The English Stavleak organizer toolkit provides checklists that you can adapt when planning a demonstration.

Top comments (0)