Last active
January 6, 2021 14:23
-
-
Save breadthe/4e0373e064873645e088a22e22b8830d to your computer and use it in GitHub Desktop.
Svelte Summit 2020 | Tim Raderschad | Modern Fetch in Svelte using Stores
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { writable } from 'svelte/store'; | |
const cache = new Map(); | |
export async function getData(url) { | |
const store = writeable(new Promise(() => {})); | |
if (cache.has(url)) { | |
store.set(Promise.resolve(cache.get(url))); | |
} | |
const load = async () => { | |
const response = fetch(url); | |
const data = response.json(); | |
cache.set(url, data); | |
store.set(Promise.resolve(data)); | |
}; | |
load(); | |
return store; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
import getData from './fetcher.js'; | |
const response = getData(url); | |
{#await $response} | |
<Spinner /> | |
{:then data} | |
<code {data}> | |
{:catch} | |
<Error /> | |
{/await} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment