<script>
/**
* This example demonstrates a manual subscription that always gets
* correct/updated $store value, and an auto subscription that does not.
*
* What we want is for value1 and value2 to reset to 0 if $store gets bigger than 2.
* It works for value2 (manual subscription), but not for value1 (reactive declaration + auto subscription).
*
* Click 'Increase $store value' 3 times to see the issue (value1 and
* value2 is no longer the same, which they should be).
*
* Interestingly enough, if we click the 'Reset $store value'
* button manually, everything seems to work as expected.
*
* Update:
* After some debugging it seems the issue boils down to the following:
* 1. The reactive declaration blocks are ran in the order they're declared, which means by the time 'resetStoreValue()' is run,
* 'value1 = $store;' has already run.
* Svelte usually tries to reorder these blocks, so that 'assigmment blocks' (in this case the block that runs 'resetStoreValue()')
* run before 'read value blocks' (in this case the block that does 'value1 = $store').
* In this case however, it isn't able to, due to 2.
* 2. By abtracting '$store = 0;' to 'resetStoreValue()', it seems Svelte doesn't understand that this is an 'assignment block'.
* What's interesting is that it only seems to understand that it's an 'assignment block' if we do '$store = 0', not if we do
* 'store.set(0)' or 'store.update((state) => 0)'.
*/
import { tick } from 'svelte';
import { writable } from 'svelte/store';
const store = writable(0);
let value1;
let value2;
$: {
// This doesn't run after 'resetTestValue()' is ran, which it (probably?) should.
console.log(1, $store);
value1 = $store;