AndiGo
AndiGo

Reputation: 1

How to iterate over svelte writable store with svelte each?

i have started to use astro and svelte. Currently i am trying to fetch some data and store it in a writable store in a JS file. In my svelte component i am using {#await} and within {:then} a {#each}.

The problem is that i get the following error from svelte "Uncaught (in promise) Error: {#each} only iterates over array-like objects."

Navigation.svelte:

<script lang="ts">
    import { getData } from "../js/helper/getData";

    const options = {
        method: "GET",
        headers: {
            "KEY": VALUE,
        },
    };

    const response = getData(
        "URL",
        options
    );
</script>

<div>
        {#await $response}
            <p>...waiting</p>
        {:then data}
            {#each data as category}
                <a
                    href="#">
                    {category.name}
                </a>
            {/each}
        {:catch error}
            <p>An error occurred!</p>
        {/await}
    </div>

getData.js:

import { writable } from "svelte/store";

const cache = new Map();

export function getData(url, option = {}) {
    const store = writable(new Promise(() => { }));

    if (cache.has(url)) {
        store.set(Promise.resolve(cache));
    }

    const load = async () => {
        const response = await fetch(url, option);
        const data = await response.json;
        cache.set(url, data);
        store.set(Promise.resolve(data));
    }

    load();

    return store;
}

Error Message: enter image description here

Upvotes: 0

Views: 920

Answers (1)

brunnerh
brunnerh

Reputation: 185117

There seems to be an error in getData:

if (cache.has(url)) {
    store.set(Promise.resolve(cache));
}

This resolves to the entire cache, which is a Map, which is not array-like. You probably wanted to do:

store.set(Promise.resolve(cache.get(url));

Upvotes: 1

Related Questions