Nuxt Tip: Cancel Fetch API Request
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:
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:
Vue Tip: Check if Component Has Event Listener Attached
Sometimes, you want to apply specific styles to a component only if it has an event listener attached.
Vue Tip: Passing Slots to Child Components
In certain scenarios, you need to pass on all slots from a parent component to the child component.