DEV Community

artydev
artydev

Posted on

2

Fectching Data with WebComponent

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>
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay