user1513388
user1513388

Reputation: 7451

Fetch with Svelte vs Sveltekit

I'm following along with the svelte tutorial here:

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

Essentially, it includes App.Svelte file and fetch.js import file.

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]
}
<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}

This all works as expected in Svelte.

However, If move the code into a Sveltekit app I'm getting the following errors in my VS Code.

enter image description here

enter image description here

enter image description here

I've put the fetch.js file in the root of the src directory and renamed the App.Svelte to getData.Svelte which is in the routesdirectory below thesrc`.

It seems that things work differently between Svelte vs Sveltekit which make the tutorial confusing. Am I missing something fundamental here?

Upvotes: 0

Views: 612

Answers (1)

hackape
hackape

Reputation: 19987

It's a TypeScript problem. I'll spare you the technical detail and just tell you a quick fix: instead of returning an array, return an object instead.

So in fetchStore function you return { data, loading, error, get }. And in svelte component you read like const { data, loading, error, get } = fetchStore(url). Basically change bracket [] to brace{} and the error will go away.

Upvotes: 0

Related Questions