DEV Community

artydev
artydev

Posted on

Swiss and Fetch

Swiss provides a functional way of defining custom elements

Here is a way to hydrate a custom element from a web request using fetch.

HTML part

<s-users id="listusers" num=10></s-users>

JS part


function liUsers (user) {
  return `
    <li>
     <img src=${user.picture.thumbnail}></img> ${user.name.first}
    </li>`
} 

function Users (el) {
  let data = null
  let users = listusers.getAttribute("users")
  users &&  ( data = JSON.parse(users))
  const view = `
    <ul>
      ${data && data.map(liUsers).join('') || "Loading.." } 
    </ul>`
  return  view 
}

async function fetchUsers (numUsers) {
  const response = await fetch(`https://randomuser.me/api/?results=${numUsers}`) 
  const data  = await response.json()
  console.log(data.results)
  return data.results
}

function displayUsers (numUsers) {
  fetchUsers(numUsers).then((data) =>  {
      listusers.setAttribute("users", JSON.stringify(data))
    }
  )
}

function main () {
  swiss.element("s-users", Users, ["users"])
  const numUsers = parseInt(listusers.getAttribute("num"))
  displayUsers (numUsers)   
}

main()



You can play with it here : Swiss&Fetch

Top comments (0)