TK
Posted on July 13, 2022
When I tried to create persited store in SvelteKit, I had to understand unscribe function like below.
<script>
import { onDestroy } from 'svelte'
import { writable } from 'svelte/store';
const count = writable(0, () => {
console.log('Start subscribing')
// Below function is called when execute unsubscribe function.
return () => console.log('Stop subscribing');
})
const increment = () => count.update(value => {
return value + 1
})
const unsubscribe = count.subscribe(value => {
console.log(value)
})
onDestroy(unsubscribe)
</script>
<button on:click={increment}>
Increment
</button>
<button on:click={unsubscribe}>
Stop subscribe
</button>
What is unsubscribe function?
If we use subscribe, we should stop the subscribing. Because when component is died, we cannot stop it and use lots of memory. So we should call unsubscribe function with onDestory
function. But it is too trouble to develop... ... so we can use $
prefix as instead.
💖 💪 🙅 🚩
TK
Posted on July 13, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
svelte NgSysV2-3.2: A Serious Svelte InfoSys: Form validation and Exception handling
August 21, 2024