user1513388
user1513388

Reputation: 7451

Svelt with Fetch and button click events

I'm probably missing something obvious but I can't get my head around this.

I have an App.Svelte

<script>
    let url = "https://www.swapi.tech/api/people/1"
    
    import fetchStore from './fetch.js'
    const [data, loading, error, get] = fetchStore(url)
</script>

<button on:click={get}>
    Fetch again
</button>

{#if $loading}
    Loading: {$loading}
{:else if $error}
    Error: {$error}
{:else}
    <pre>{JSON.stringify($data, null, 2)}</pre>
{/if}

and a fetch.js

import { writable } from 'svelte/store'

export default function (url) {
    const loading = writable(false)
    const error = writable(false)
    const data = writable({})
    
    async function get() {
        loading.set(true)
        error.set(false)
        try {
            const response = await fetch(url)
            data.set(await response.json())
        } catch(e) {
            error.set(e)
        }
        loading.set(false)
    }
    
    get()
    
    return [ data, loading, error, get]
}

Here's the REPL:

https://svelte.dev/repl/a74f1ed8e3eb4aec82cb743e13443ee4?version=3.48.0

When the page loads it runs the fetch and the button can be used to fetch again. However, I want to build a page with multiple buttons that only fetches and renders when the button is clicked.

I can't work out how to do this since there some magic happening within Svelte that I don't understand. Could somebody explain and maybe show how to do this.

Upvotes: 0

Views: 387

Answers (1)

CD..
CD..

Reputation: 74176

You can remove the get() in your fetch function, so the get will be called only by clicking the button.

Upvotes: 2

Related Questions