·
0 min read

Nuxt Tip: Cancel Fetch API Request

MH

Michael Hoffmann

@mokkapps

Nuxt Tip: Cancel Fetch API Request Image

It's a common use case to cancel an API request, for example, when a user navigates away from a page.

Cancel Fetch API Request

In Nuxt 3, you can use the signal parameter from AbortController with the globally available $fetch helper to cancel an API request:

Component.vue
<script setup>
const abortController = new AbortController();

const { status } = useAsyncData(
  'testApi',
  () =>
    $fetch('https://hub.dummyapis.com/delay?seconds=1', {
      signal: abortController.signal,
    }),
);

const cancelRequest = () => {
  abortController.abort();
};
</script>

<template>
  <div>
    <span>Status: {{status}}</span>
    <button @click="execute">Trigger Request</button>
    <button @click="cancelRequest">Cancel Request</button>
  </div>
</template>

StackBlitz

Try it yourself in this StackBlitz:

If you liked this Vue tip, follow me on BlueSky to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter :

I will never share any of your personal data. You can unsubscribe at any time.