I'm kind of new to Svelte. I have a simple store defined as follows:
import { writable } from 'svelte/store';
export let store = writable({});
Then, in my main app component, I do the following:
<script>
import {store} from './store.js'
async function functionOne() {
console.log("functionOne called")
}
function setStore() {
$store = {foo: 'bar'}
console.log(`Store is set, equals: ${JSON.stringify($store)}`)
return true
}
</script>
<main>
{#await functionOne()}
Loading...
{:then _}
{#if setStore()}
{console.log(`We are inside the #if block with store=${JSON.stringify($store)}`)}
{/if}
{/await}
</main>
When I run this, I get the following log:
functionOne called
Store is set, equals: {"foo": "bar"}
We are inside the #if block with store={}
We are inside the #if block with store={"foo": "bar"}
What seems to be happening is:
- Svelte initializes the app, it calls the function in the
#awaitblock, and moves on to the:thenclause. - There, it finds an
#ifblock and evaluates the condition. The condition sets the store (the result is logged in line 2). - Svelte then moves over to the body of the
#ifblock. Here the store is not set (!!!) - Then, the body of the
#ifblock runs again with the store value set
My question is: What is going on? If the store is set in step 2 (as we can see from the fact that its value is logged), why does Svelte execute the body of the #if block as if it wasn't in step 3?
DOM updates are asynchronous, so changes may only be reflected in the next update cycle. In general you should avoid mutating state via functions in the markup, it is harder to reason about and does not play well with the asynchronous nature of the updates.