Joe Ralphin
Joe Ralphin

Reputation: 39

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>

Upvotes: 2

Views: 6216

Answers (2)

nash11
nash11

Reputation: 8690

Svelte's reactivity is triggered by assignments. (Source: docs)

So if you want to push more quotes into non, you have to do so using non = [...non, json];

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

    onMount(() => {
        getRandomQuote();
    });

    async function getRandomQuote() {
        gettingQuote = true;
        const res = await fetch("https://api.quotable.io/random");
        const json = await res.json();
        non = [...non, json];
        gettingQuote = false;
    }
</script>

<div>
    {#each non as {author, content}}
        <p>{content} - {author}</p>
    {/each}
    <button on:click={getRandomQuote} disabled={gettingQuote}>Get Quote</button>
    {#if gettingQuote}
        <span>Getting Quote...</span>
    {/if}
</div>

Here is a working example.

Upvotes: 4

CD..
CD..

Reputation: 74176

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

Upvotes: 5

Related Questions