admin管理员组文章数量:1278917
I am trying to display data I request by fetch from API. Everything works well except fetch.
This is my ponent named Items.svelte
:
<script>
let items = [];
async function load({ fetch }) {
const url = "../r/api/items/all";
let res = await fetch(url);
if (res.ok) {
return {
props: {
items: await res.json(),
},
};
}
return {
status: res.status,
error: new Error(),
};
}
</script>
{#each items as item}
<header>
<h2>{item.title}</h2>
<p>{item.body}</p>
</header>
{/each}
This is App.svelte
:
<script>
import Items from '$lib/Items.svelte';
</script>
<Items />
What am I doing wrong?
I am trying to display data I request by fetch from API. Everything works well except fetch.
This is my ponent named Items.svelte
:
<script>
let items = [];
async function load({ fetch }) {
const url = "../r/api/items/all";
let res = await fetch(url);
if (res.ok) {
return {
props: {
items: await res.json(),
},
};
}
return {
status: res.status,
error: new Error(),
};
}
</script>
{#each items as item}
<header>
<h2>{item.title}</h2>
<p>{item.body}</p>
</header>
{/each}
This is App.svelte
:
<script>
import Items from '$lib/Items.svelte';
</script>
<Items />
What am I doing wrong?
Share Improve this question edited Feb 20, 2022 at 10:24 vhs 10.1k3 gold badges72 silver badges77 bronze badges asked Sep 6, 2021 at 13:32 anarkianarki 651 silver badge5 bronze badges2 Answers
Reset to default 6According to the documentation ---> https://kit.svelte.dev/docs/loading
You are missing the context="module" script section. It should be :
<script context="module">
export async function load({ fetch }) {
let res = await fetch('../r/api/items/all');
if (res.ok) {
return {
props: {
items: await res.json()
}
};
}
return {
status: res.status,
error: new Error()
};
}
</script>
<script>
export let items = []
</script>
{#each items as item}
<header>
<h2>{item?.title}</h2>
<p>{item?.body}</p>
</header>
{/each}
In the docs (https://kit.svelte.dev/docs/loading) it says: "A ponent that defines a page or a layout can export a load function that runs before the ponent is created."
You can't use load from a ponent, only from a page or layout.
see also https://stackoverflow./a/67429568/1390405
本文标签: javascriptCan39t fetch data from API in SvelteKitStack Overflow
版权声明:本文标题:javascript - Can't fetch data from API in SvelteKit - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741295947a2370817.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论