Last active
March 25, 2022 01:05
-
-
Save Theo-Steiner/e7fdbbdde224e5d53c35da26844902bd to your computer and use it in GitHub Desktop.
Svelte async store initiation with fetched results
This file contains hidden or 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
How to asynchronously set the contents of a store based on a fetch call. |
This file contains hidden or 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 { questionStore } from "./store.js"; | |
</script> | |
{#each $questionStore as {question}} | |
<p> | |
{question} | |
</p> | |
{/each} |
This file contains hidden or 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 { 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