Reputation: 39
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
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
Reputation: 74176
Because Svelte's reactivity is triggered by assignments, using array methods like
push
andsplice
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