Sometimes you have to display results coming from several requests.
Would not it be nice to simply use web component passing the url to be requested ?
<fetch-randomuser data-num="5">
<a href="https://randomuser.me/api/">
Random Users
</a>
</fetch-randomuser>
Here is the code : (Demo)
import van from "./van.js"
const { div, button, span, "user-card": UserCard, img } = van.tags
const { end, begin } = van
const bdiv = () => begin(div())
function Card(user) {
let
thumbnail = user.picture.thumbnail,
user_name = user.name.first,
user_email = user.email,
user_city = user.location.city;
let user_card = begin(UserCard())
// identity
div({ class: 'ident' },
img({ src: thumbnail }),
div({ style: 'text-align:center' },
user_name
)
)
// address
div({ class: 'address' },
div(user_email),
div(user_city),
)
button (
{
onclick: () => alert(`Hy, I am ${user_name}`),
}, "Hy"
)
end()
return user_card
}
function Users(users) {
console.log(users)
return users.map(Card)
}
class FetchUser extends HTMLElement {
async connectedCallback() {
let numusers = Number(this.dataset.num)
let link = this.querySelector("a");
let req = await fetch(`${link.href}?results=${numusers}`)
let resp = await req.json()
van.add(this, Users(resp.results))
}
}
customElements.define("fetch-randomuser", FetchUser);
Top comments (0)