-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Description
Describe the problem
Whenever you make async requests to backend in your components you also need to remember to abort them. Otherwise resources won't be cleared immediately on the component destruction, but rather will wait until the request is finished. In certain scenarios that could even introduce a memory leak.
For the sake of future examples let's imagine that we have some wrapper functions for fetch
for improved DX - post
and get
.
Currently the solution is to do the following:
<script>
const ctrl = new AbortController()
onDestroy(() => ctrl.abort())
let s = $state()
post('/something', { signal: ctrl.signal })
.then(res => {
// if not aborted this will hold memory
s = res
})
onMount(() => {
get('/somethingelse', { signal: ctrl.signal })
.then(res => {
// if not aborted this will hold memory
s = res
})
})
</script>
Hello, world
However my experience seems to show, that be it Svelte or React or anything else - developers tend to forget to do this, which leads to the problems described.
Now in recent version getAbortSignal
got introduced, which already greatly helps to avoid this problem whenever call to the function happens in $derived
or $effect
, but not in script body or onMount
.
If we widen it's scope then we can do something like this:
export function post(url, opts) {
let signal = opts.signal
if (!signal) {
try {
signal = getAbortSignal()
} catch {}
}
return fetch(url, { method: 'POST', signal })
}
<script>
let s = $state()
post('/something')
.then(res => {
// no longer holds memory, because aborted automatically
s = res
})
onMount(() => {
get('/somethingelse', { signal: ctrl.signal })
.then(res => {
// no longer holds memory, because aborted automatically
s = res
})
})
</script>
Hello, world
In this case we can greatly improve the situation by ensuring that all the requests that happens in components will be aborted automatically whenever component destroys. And it doesn't require a developer to think about it entirely. It just happens.
Describe the proposed solution
Widen getAbortSignal to also be tied to component lifecycle.
In our project we have a mini runtime that schedules requests, so getAbortSignal
could be utilized on the runtime level and greatly improve DX for developers doing product features.
We already utilize it so requests get automatically aborted in deriveds or effects and it great!
REPL showing it currently doesn't work like this.
Importance
would make my life easier