Reputation: 85
As I understand, when using Svelte store with $ prefixed it's automatically subscribed to value changes.
Having the following code, whenever users.name store value is changed it should trigger one of the two statements.
<script>
if (!$userS.name) {
list = Promise.reject({message:'You are not allowed to view this section!'});
} else {
list = getList('api/carousel/' + escape(term));
}
</script>
But the only way the previous code is working is when the if statement it's prefixed by "$:".
$: if (!$userS.name) { ...
So why is need the extra reactive dollar sign if it's already subscribed to store value changes?
Upvotes: 2
Views: 1971
Reputation: 25001
Your component init script, that is the code inside the<script>
tag, is not reactive. It runs once when your component is created and that's all. Think class constructor.
Only the code in reactive blocks $:
is kept in sync and reruns when (reactive) variables they contain change.
The $
prefix gives you the value inside the store. In your example, the user
variable is the store itself. console.log
it, you'll see it is an object with a subscribe
method etc. The prefixed variable gives you the value inside the store. Behind the scene, Svelte makes a subscription to the store (i.e. calls its subscribe
method) when your component is created, and unsubscribes when it is destroyed.
Meanwhile, if the value changes, the $
prefixed variable will be reactive. But it will only have an effect if it sits in a reactive context. That is, either a reactive expression/statement $:
, or in the markup. This is true for any reactive source (props, top level variables...).
Upvotes: 2