Reputation: 355
I'm new to working with svelte.
I want to use the result of a promise in my await block to bind this to another component.
But the variable bound to the other component always stays undefined.
{#await somePromise then promiseResult}
<div> promiseResult </div>
{/await}
<NewComponent bind:promiseResult />
Any tips
Upvotes: 1
Views: 1458
Reputation: 7699
promiseResult
must be in component scope if you want to use it with the binding.
<script>
let promiseResult
async function foo() {
//..
promiseResult = result
}
</script>
{#await foo() then _ }
<div> {promiseResult} </div>
{/await}
<NewComponent bind:promiseResult />
Here only the top level variable is set and the function doesn't return anything, so a placeholer _
can be used inside the await block to illustrate that in both places the main promiseResult
is referenced.
While it would also be possible to set and return the value, this might lead to confusion if in both places the same variable name is used. The one inside the #await block can only be read and not modifed. REPL
<script>
import NewComponent from './NewComponent.svelte'
let promiseResult
function foo() {
return new Promise(res => {
promiseResult = 'result'
res('result')
})
}
</script>
{#await foo() then promiseResult}
<!-- promiseResult here read only local variable inside #await block -->
<div on:click={() => promiseResult = 'will give error'}>
{promiseResult}
</div>
{/await}
<NewComponent bind:promiseResult />
<!-- only modifies top level variable -->
<button on:click={() => promiseResult = 'newValue'}>
change promiseResult
</button>
Upvotes: 2