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
  • The props are missing curly braces let {people} = $props(); – Corrl Commented Jan 19 at 21:50
  • Oof, thank you. – zmb Commented Jan 19 at 22:28
Add a comment  | 

2 Answers 2

Reset to default 1

The 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