Skip to content

Instantly share code, notes, and snippets.

@mjstahl
Last active July 24, 2019 18:43
Show Gist options
  • Save mjstahl/0f54889d7fae1744129b656ea860f48c to your computer and use it in GitHub Desktop.
Save mjstahl/0f54889d7fae1744129b656ea860f48c to your computer and use it in GitHub Desktop.
Simple async fetch example in Elementree
<!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>
<!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