Skip to content

Instantly share code, notes, and snippets.

@viniciusCamargo
Created October 11, 2017 20:43
Show Gist options
  • Save viniciusCamargo/8f194d54eaf3952cf6231f9c29369de6 to your computer and use it in GitHub Desktop.
Save viniciusCamargo/8f194d54eaf3952cf6231f9c29369de6 to your computer and use it in GitHub Desktop.
mithril - fetch example
const root1 = document.getElementById('root1')
const root2 = document.getElementById('root2')
const root3 = document.getElementById('root3')
const l = console.log.bind(this)
const api = {
path: 'https://jsonplaceholder.typicode.com',
getPostById(id) {
return m.request({ url: `${this.path}/posts/${id}` })
},
getPosts() {
return m.request({ url: `${this.path}/posts` })
}
}
const Post = ({ title, body }) => m('div', [m('h2', title), m('p', body)])
const PostPage = {
data: {
post: {},
error: ''
},
async oninit() {
try {
const request = await api.getPostById(1)
this.data.post = request
} catch (error) {
this.data.error = error.message
}
},
view() {
const { error, post } = this.data
return error
? m('p', error)
: Post(post)
}
}
const Posts = {
data: {
posts: [],
error: ''
},
async oninit() {
try {
const request = await api.getPosts()
this.data.posts = request
} catch (error) {
this.data.error = error.message
}
},
view() {
const { error, posts } = this.data
return error
? m('p', error)
: posts.map(Post)
}
}
m.mount(root1, PostPage)
m.mount(root2, Posts)
m.render(root3, m('main', [
m('h1', {class: 'title'}, 'Yo'),
m('button', { onclick: () => l('oi') }, 'my button')
]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment