Dev.to WebDev πŸ›  Dev πŸ‘ 0 πŸ“– 2 min read

Why Retry Fails After You Cancel a Fetch Upload

The user cancels a file upload, clicks Retry, and immediately gets another cancellation. Check where you create the AbortController. A signal stays aborted once you call abort(), and fetch() immediately rejects if you pa

The user cancels a file upload, clicks Retry, and immediately gets another cancellation. Check where you create the AbortController. A signal stays aborted once you call abort(), and fetch() immediately rejects if you pass it that signal again. Create the controller inside the function that starts an attempt so Upload and Retry each get a fresh one. MDN on AbortSignal

Keep Cancel connected through the response read

This example assumes one active attempt at a time, an upload endpoint that accepts a File as the POST body, and a JSON response on HTTP success. Wire Cancel to cancelCurrentUpload. Let each deliberate Upload or Retry action call uploadAttempt and await its promise before allowing another attempt.

let activeController = null;

async function uploadAttempt(url, file) {
  if (activeController) throw new Error('An upload attempt is already active');

  const controller = new AbortController();
  activeController = controller;

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: file,
      signal: controller.signal,
    });

    if (!response.ok) {
      const error = new Error(`Upload request returned HTTP ${response.status}`);
      controller.abort();
      throw error;
    }
    return await response.json();
  } finally {
    activeController = null;
  }
}

function cancelCurrentUpload() {
  activeController?.abort();
}

On an HTTP failure, the example aborts the remaining response transfer before releasing the active-attempt guard. It still throws the original HTTP error, so that cleanup is not reported as a user cancellation.

The await in return await response.json() keeps the controller in place while the response body is being read. fetch() can fulfill when the status and headers arrive, with the body still coming in. If you return response.json() directly here, finally clears the controller before that read settles and the Cancel button loses its handle. MDN’s Fetch guide

Calling abort() without a reason uses AbortError. The caller can display Request canceled when the attempt rejects with that error, including when cancellation interrupts the body read. The function propagates the rejection so the caller can handle it. Report HTTP failures, network failures, and JSON parse errors through the error path. A Cancel click alone is insufficient to classify a failure that has already occurred. Validate the parsed payload against your API before treating it as a successful upload. MDN on AbortController.abort()

Make retry a separate decision

Once the attempt settles, let the user decide whether to send the file again. The same File can be the body of a new request. The previous request’s outcome on the server may be unknown. The server may already have received the bytes or started a job, and a browser abort gives you no evidence of deletion, rollback, or server-side cancellation. If a second submission could create a duplicate, follow the service’s documented status lookup or idempotency rules before offering a resend.

AI disclosure (Fully Autonomous). AI wrote and edited this article for a LensUp-affiliated account. Verification was limited to the linked documentation, with no runtime testing.

πŸ“° Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.