A very thin wrapper around
fetchwith Svelte store integration for request states.
When making a web app, I always end up adding ongoing requests to some central state array so that I can compute when my application is "loading". That's basically what this is: a thin wrapper around the native fetch API, with importable Svelte readables that can be used to show spinners and blocking modals for various request states.
npm i -S svelte-fetch or yarn add svelte-fetch
<script>
import Fetch, {
hasAny,
hasBlocking,
hasBackground
} from "svelte-fetch"
const fetch = new Fetch()
const [res1, res2, res3] = await Promise.all([
// Makes a regular request (typically shows a spinner in the UI)
fetch.get("http://localhost:3000/dev/ping?delay=1000"),
//Makes a blocking request (typically block UI interaction)
fetch.blocking.get("http://localhost:3000/dev/ping?delay=1000"),
//Makes a background request (typically invisible to the UI)
fetch
.background
.expect(JSON)
.get("http://localhost:3000/dev/ping?delay=1000"),
])
console.log(res1, res2, res3)
</script>
{#if $hasAny}
Loading!
{/if}
{#if $hasBlocking}
Loading (blocked)!
{/if}
{#if $hasBackground}
Loading (background)!
{/if}
SvelteFetch.requestA wrapper around fetch.
SvelteFetch.getShorthand for using SvelteFetch.request with the {method:"GET"} option.
SvelteFetch.putShorthand for using SvelteFetch.request with the {method:"PUT"} option.
SvelteFetch.postShorthand for using SvelteFetch.request with the {method:"POST"} option.
SvelteFetch.destroyShorthand for using SvelteFetch.request with the {method:"DELETE"} option.
SvelteFetch.backgroundAdds the next request to the background queue (available from the export hasBackground), and removes it when it completes.
const fetch = new SvelteFetch()
const data = await fetch.background.get(`https://endpoint`)
SvelteFetch.blockingAdds the next request to the blocking queue (available from the export hasBlocking), and removes it when it completes.
const fetch = new SvelteFetch()
const data = await fetch.blocking.get(`https://endpoint`)
SvelteFetch.expectTells the request what data to expect next. Supports:
JSONNumber (will use the JSON parser)StringImageBlob
If SvelteFetch.expect is not used, data from the request is parsed using the Content-Type header. const fetch = new SvelteFetch()
const data = await fetch.expect(JSON).get(`https://endpoint`)