Skip to content

Instantly share code, notes, and snippets.

@Theo-Steiner
Last active March 25, 2022 01:05
Show Gist options
  • Save Theo-Steiner/e7fdbbdde224e5d53c35da26844902bd to your computer and use it in GitHub Desktop.
Save Theo-Steiner/e7fdbbdde224e5d53c35da26844902bd to your computer and use it in GitHub Desktop.
Svelte async store initiation with fetched results
How to asynchronously set the contents of a store based on a fetch call.
<script>
import { questionStore } from "./store.js";
</script>
{#each $questionStore as {question}}
<p>
{question}
</p>
{/each}
import { readable } from "svelte/store"
export const questionStore = readable([], async set => set(await getQuestionData()))
async function getQuestionData() {
const url =
"https://opentdb.com/api.php?amount=10&category=27&difficulty=easy&type=multiple"
const response = await fetch(url);
const data = await response.json();
return data.results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment