admin管理员组文章数量:1319470
I'm really struggling to understand reactivity in Svelte 5.
I've created a little class to encapsulate a data fetch operation:
class DataResponse {
data = $state([]);
error = $state();
isLoading = $state(false);
}
And a useFetchData
helper that kicks off a fetch and returns an instance of this class (which is updated by reassigning data
when the response is received).
export function useFetchData() {
const resp = new DataResponse();
async function fetchData() {
resp.isLoading = true;
try {
const response = await fetch("/?results=5");
const j = await response.json();
resp.data = j.results;
resp.error = undefined;
} catch (err) {
resp.error = err;
resp.data = undefined;
console.error(err);
} finally {
resp.isLoading = false;
}
}
fetchData();
return resp;
}
If I use this data directly at the call site, reactivity works as I'd expect and the UI updates when the API call returns.
<script>
import { useFetchData } from "./useFetchData.svelte.js";
const resp = useFetchData();
</script>
{#each response.data as person}
<div>{person.name.first} {person.name.last}</div>
{/each}
When I extract the UI logic into a separate component and try to pass this data to a child component as a prop, I lose reactivity and the UI never updates. What am I doing wrong?
<script>
import { useFetchData } from "./useFetchData.svelte.js";
const resp = useFetchData();
</script>
<People people={rest.data} />
<!-- People.svelte -->
<script>
let people = $props();
</script>
<h1>People</h1>
{#each people as person}
<div>{person.name.first} {person.name.last}</div>
{/each}
I've prepared a minimal example in the playground: /playground/455ad944b0cd42fdbee891a488ad372f?version=5.19.0
I'm really struggling to understand reactivity in Svelte 5.
I've created a little class to encapsulate a data fetch operation:
class DataResponse {
data = $state([]);
error = $state();
isLoading = $state(false);
}
And a useFetchData
helper that kicks off a fetch and returns an instance of this class (which is updated by reassigning data
when the response is received).
export function useFetchData() {
const resp = new DataResponse();
async function fetchData() {
resp.isLoading = true;
try {
const response = await fetch("https://randomuser.me/api/?results=5");
const j = await response.json();
resp.data = j.results;
resp.error = undefined;
} catch (err) {
resp.error = err;
resp.data = undefined;
console.error(err);
} finally {
resp.isLoading = false;
}
}
fetchData();
return resp;
}
If I use this data directly at the call site, reactivity works as I'd expect and the UI updates when the API call returns.
<script>
import { useFetchData } from "./useFetchData.svelte.js";
const resp = useFetchData();
</script>
{#each response.data as person}
<div>{person.name.first} {person.name.last}</div>
{/each}
When I extract the UI logic into a separate component and try to pass this data to a child component as a prop, I lose reactivity and the UI never updates. What am I doing wrong?
<script>
import { useFetchData } from "./useFetchData.svelte.js";
const resp = useFetchData();
</script>
<People people={rest.data} />
<!-- People.svelte -->
<script>
let people = $props();
</script>
<h1>People</h1>
{#each people as person}
<div>{person.name.first} {person.name.last}</div>
{/each}
I've prepared a minimal example in the playground: https://svelte.dev/playground/455ad944b0cd42fdbee891a488ad372f?version=5.19.0
Share Improve this question edited Jan 20 at 8:38 brunnerh 186k30 gold badges357 silver badges430 bronze badges asked Jan 19 at 20:25 zmbzmb 7,8877 gold badges42 silver badges57 bronze badges 2 |2 Answers
Reset to default 1The props syntax in People
is off, you get all props as the object. You probably intended it to be this:
let { people } = $props();
You can also get all props and access the property separately if you want:
let props = $props();
{#each props.people as person} ...
I have upvoted brunnerh's answer and that's the answer to your problem.
I will, however, volunteer a better way of doing this.
export async function fetchData(url, fetchOptions?) {
// Set up auth header or whatever. Then:
const response = fetch(url, fetchOptions);
// I will asume, for simplicity, that the call succeeds with an OK response.
return await response.json();
}
Just like that, you can use {#await}
with the returned promise. You don't need all that convoluted helper and you certainly don't need the isLoading
flag. Maybe you come from React or similar? Fet that guy. Svelte has your back. :-)
<script>
import { fetchData } from "./fetchData.js";
const dataPromise = fetchData('my/url');
</script>
<People people={dataPromise} />
<!-- People.svelte -->
<script>
let { people } = $props();
</script>
<h1>People</h1>
{#await people}
<div>Loading people. Please wait...</div>
{:then peopleData}
{#each peopleData as person}
<div>{person.name.first} {person.name.last}</div>
{/each}
{:catch cause}
<!-- do something with cause and alert the user -->
{/await}
The {#await}
block is the HTML template version of await
and as you can see, it can cover the needs for the isLoading
flag and the error
piece of data you have in your helper class.
If you want to have a more robust fetching helper, I created dr-fetch that provides a couple helper functions to deal with header-setting chores and on top of that, allows you to type the response body in a per-http-status-code manner.
本文标签: sveltePassing reactive props to childrenStack Overflow
版权声明:本文标题:svelte - Passing reactive props to children - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742059966a2418523.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
let {people} = $props();
– Corrl Commented Jan 19 at 21:50