Adjust store unsubscribe tutorial section (#5975)

The `unsubscribe` function in the first step was without any usage, which lead to confusion
pull/6383/head
Andrew Lee 4 years ago committed by GitHub
parent 2ae79f6815
commit 791104d9fe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -6,7 +6,7 @@
let count_value; let count_value;
const unsubscribe = count.subscribe(value => { count.subscribe(value => {
count_value = value; count_value = value;
}); });
</script> </script>
@ -15,4 +15,4 @@
<Incrementer/> <Incrementer/>
<Decrementer/> <Decrementer/>
<Resetter/> <Resetter/>

@ -24,4 +24,4 @@ Finally, in `Resetter.svelte`, implement `reset`:
function reset() { function reset() {
count.set(0); count.set(0);
} }
``` ```

@ -6,7 +6,7 @@
let count_value; let count_value;
const unsubscribe = count.subscribe(value => { count.subscribe(value => {
count_value = value; count_value = value;
}); });
</script> </script>
@ -15,4 +15,4 @@
<Incrementer/> <Incrementer/>
<Decrementer/> <Decrementer/>
<Resetter/> <Resetter/>

@ -2,9 +2,17 @@
title: Auto-subscriptions title: Auto-subscriptions
--- ---
The app in the previous example works, but there's a subtle bug — the `unsubscribe` function never gets called. If the component was instantiated and destroyed many times, this would result in a *memory leak*. The app in the previous example works, but there's a subtle bug — the store is subscribed to, but never unsubscribed. If the component was instantiated and destroyed many times, this would result in a *memory leak*.
One way to fix it would be to use the `onDestroy` [lifecycle hook](tutorial/ondestroy): Start by declaring `unsubscribe` in `App.svelte`:
```js
const unsubscribe = count.subscribe(value => {
count_value = value;
});
```
You now declared `unsubscribe`, but it still needs be to called, for example through the `onDestroy` [lifecycle hook](tutorial/ondestroy):
```html ```html
<script> <script>
@ -43,4 +51,4 @@ It starts to get a bit boilerplatey though, especially if your component subscri
You're not limited to using `$count` inside the markup, either — you can use it anywhere in the `<script>` as well, such as in event handlers or reactive declarations. You're not limited to using `$count` inside the markup, either — you can use it anywhere in the `<script>` as well, such as in event handlers or reactive declarations.
> Any name beginning with `$` is assumed to refer to a store value. It's effectively a reserved character — Svelte will prevent you from declaring your own variables with a `$` prefix. > Any name beginning with `$` is assumed to refer to a store value. It's effectively a reserved character — Svelte will prevent you from declaring your own variables with a `$` prefix.

Loading…
Cancel
Save