Last active
June 25, 2021 17:14
-
-
Save wobsoriano/c33f3b72e7e6a138057528439b143718 to your computer and use it in GitHub Desktop.
A Vue 3 hook to cancel promises when a component is unmounted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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