Cannot bind to a variable declared with {#await … then} or {:catch} blocks}

huangapple go评论51阅读模式
英文:

Cannot bind to a variable declared with {#await ... then} or {:catch} blocks}

问题

这是一个很好的错误解释,但我不知道如何解决它。
我有一个+layout.js文件,返回一个异步的load函数:

import { api } from '$lib/utils/api';

/** @type {import('./$types').PageLoad} */
export async function load() {
    const fetchUserData = async () => {
        return await api.auth.user();
    };

    return {
        stream: {
            user: fetchUserData()
        }
    };
}

然后在+page.svelte中,我使用{#await}加载这个数据:

<script>
  export let data;
  let { stream } = data;
</script>

{#await stream.user then user}
<input type="text" bind:value={user.data.gender} />
{/await}

由于在等待完成之前我没有这些用户数据,所以我不知道如何将其绑定到输入框,如果我不能使用bind:value的话。我在文档中找不到任何相关信息。

英文:

This is a nice error explanation but I don't know how to solve it.
I have a +layout.js that returns a load function async:

import { api } from &#39;$lib/utils/api&#39;;

/** @type {import(&#39;./$types&#39;).PageLoad} */
export async function load() {
	const fetchUserData = async () =&gt; {
	    return await api.auth.user();
	};

	return {
		stream: {
			user: fetchUserData()
		}
	};
}

Then in the +page.svelte I load this data with {#await}

&lt;script&gt;
  export let data;
  let { stream } = data;
&lt;/script&gt;

{#await stream.user then user}
&lt;input type=&quot;text&quot; bind:value={user.data.gender} /&gt;
{/await}

Since I don't have those user data before the await finishes, I don't know how to bind it to the input if I cannot use bind:value. I cannot find anything from the documentation.

答案1

得分: 1

你可以将块的内容提取到一个单独的组件中。我强烈建议这样做,因为 user 只在 {#await} 块中可用,否则无法直接在 &lt;script&gt; 部分中使用。

{#await ... then user}
	&lt;UserEditor {user} /&gt;
{/await}

然后,在 UserEditor 内,你可以像往常一样进行绑定。

&lt;script&gt;
	export let user;
&lt;/script&gt;
&lt;input bind:value={user.data.gender} /&gt;
英文:

You can extract the contents of the block to a separate component. I would recommend this anyway because user is scoped to the {#await} block and cannot be worked with directly in the &lt;script&gt; part otherwise.

{#await ... then user}
	&lt;UserEditor {user} /&gt;
{/await}

Inside UserEditor you then can bind as usual.

&lt;script&gt;
	export let user;
&lt;/script&gt;
&lt;input bind:value={user.data.gender} /&gt;

huangapple
  • 本文由 发表于 2023年6月21日 23:32:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76524959.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定