Skip to content

Instantly share code, notes, and snippets.

@breadthe
Last active January 6, 2021 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save breadthe/4e0373e064873645e088a22e22b8830d to your computer and use it in GitHub Desktop.
Save breadthe/4e0373e064873645e088a22e22b8830d to your computer and use it in GitHub Desktop.
Svelte Summit 2020 | Tim Raderschad | Modern Fetch in Svelte using Stores
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;
}
<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