Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fetch an remote API with svelte?

I am fetching a quote from an API and the fetching seems to work, because the first console.log is being called correctly, but second is not. The content is a field in the json object from the API.

<script>
    import { onMount } from "svelte";
    let non = [];


    onMount(async function() {
        const res = await fetch("https://api.quotable.io/random");
        const json = await res.json();
        non.push(json);
        console.log(non);
    });

</script>

<div>
   {#each non as {content}}
   <p>{content}{console.log(content)}</p>
   {/each}
</div>
like image 395
Joe Ralphin Avatar asked Dec 14 '25 18:12

Joe Ralphin


1 Answers

Because Svelte's reactivity is triggered by assignments, using array methods like push and splice won't automatically cause updates.

In yor example, if you replace non.push(json) with non = [json] it seems to work.

https://svelte.dev/tutorial/updating-arrays-and-objects

like image 50
CD.. Avatar answered Dec 17 '25 08:12

CD..



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!