Last active
March 10, 2020 11:05
-
-
Save liposo/0f3bf02380a20a4c5e10d1b3823f216b to your computer and use it in GitHub Desktop.
Example of using fetch with await block in Svelte
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> | |
$: rates = []; | |
async function fetchData() { | |
const res = await fetch("https://api.exchangeratesapi.io/latest"); | |
const data = await res.json(); | |
if (res.ok) { | |
for (const [key, value] of Object.entries(data.rates)) { | |
rates.push({currency: key, value: value}); | |
} | |
return data; | |
} else { | |
throw new Error(data); | |
} | |
} | |
</script> | |
<style> | |
ul { | |
list-style: none; | |
} | |
li { | |
border: 1px solid black; | |
padding: 5px; | |
display: flex; | |
flex-direction: row; | |
justify-content: space-between; | |
} | |
</style> | |
<main> | |
{#await fetchData()} | |
<p>...waiting</p> | |
{:then data} | |
<h3>Base currency: {data.base}</h3> | |
<ul> | |
{#each rates as rate, i} | |
<li> | |
<div>{rate.currency}</div> | |
<div>{rate.value}</div> | |
</li> | |
{/each} | |
</ul> | |
{:catch error} | |
<p style="color: red">{error.message}</p> | |
{/await} | |
</main> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment