Javascript is required
·
0 min read

Nuxt Tip: Cancel Fetch API Request

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
1<script setup>
2const abortController = new AbortController();
3
4const { status } = useAsyncData(
5  'testApi',
6  () =>
7    $fetch('https://hub.dummyapis.com/delay?seconds=1', {
8      signal: abortController.signal,
9    }),
10);
11
12const cancelRequest = () => {
13  abortController.abort();
14};
15</script>
16
17<template>
18  <div>
19    <span>Status: {{status}}</span>
20    <button @click="execute">Trigger Request</button>
21    <button @click="cancelRequest">Cancel Request</button>
22  </div>
23</template>

StackBlitz

Try it yourself in this StackBlitz:

If you liked this Vue tip, follow me on X 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.