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
#await
block, and moves on to the:then
clause. - There, it finds an
#if
block 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
#if
block. Here the store is not set (!!!) - Then, the body of the
#if
block 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?
A better solution would be:
Now import this in your component and access it directly.
You can call methods like update to update value of the store.
Checkout this enter link description here for svelte store example.