Skip to content

Instantly share code, notes, and snippets.

@wobsoriano
Last active June 25, 2021 17:14
Show Gist options
  • Save wobsoriano/c33f3b72e7e6a138057528439b143718 to your computer and use it in GitHub Desktop.
Save wobsoriano/c33f3b72e7e6a138057528439b143718 to your computer and use it in GitHub Desktop.
A Vue 3 hook to cancel promises when a component is unmounted
<template>
<button @click="ping">Ping</button>
</template>
<script setup>
import useUnmountSignal from './useUnmountSignal';
const unmountSignal = useUnmountSignal();
const ping = () => {
fetch('https://ping.example.com', { signal: unmountSignal })
}
</script>
import { onUnmounted } from 'vue';
export default function useUnmountSignal() {
const abortController = new AbortController();
onUnmounted(() => {
abortController.abort();
});
return abortController.signal;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment