Last active
July 24, 2019 18:43
-
-
Save mjstahl/0f54889d7fae1744129b656ea860f48c to your computer and use it in GitHub Desktop.
Simple async fetch example in Elementree
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
<!DOCTYPE html> | |
<html> | |
<body> | |
<script type="module"> | |
import { merge, prepare, render } from 'https://unpkg.com/elementree' | |
function Hello (state) { | |
if (!state.email) state.requestUser() | |
return render` | |
<body> | |
<p>Hello! ${state.email}</p> | |
<button onclick=${() => state.nextEmail()}>Next Email</button> | |
</body> | |
` | |
} | |
const HelloState = { | |
id: 1, | |
email: '', | |
nextEmail: function () { | |
this.email = null | |
this.id += 1 | |
}, | |
requestUser: async function () { | |
const response = await fetch(`https://reqres.in/api/users/${this.id}`) | |
const { data } = await response.json() | |
this.email = data.email | |
} | |
} | |
merge('body', prepare(Hello, HelloState)) | |
</script> | |
</body> | |
</html> |
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
<!DOCTYPE html> | |
<html> | |
<body> | |
<script type="module"> | |
import { merge, prepare, render } from 'https://unpkg.com/elementree' | |
function Hello (state) { | |
if (!state.result) { | |
fetch('https://httpbin.org/get') | |
.then(resp => resp.json()) | |
.then(value => state.result = value && value.origin) | |
} | |
return render` | |
<body> | |
<p>${ !state.result ? 'LOADING....' : state.result }</p> | |
</body> | |
` | |
} | |
merge('body', prepare(Hello, {})) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment