Display JSON results with VanJS
Tags: vanjs
Published: 2023-05-25 07:56:28

This example show how easy it is to display a result from an API call with VanJS

[Demo](https://flems.io/#0=N4IgtglgJlA2CmIBcA2ADAOgKwHYA0IAZhAgM7IDaoAdgIZiJIgYAWALmLCAQMYD21NvEHIQAHigQAbgAIesWqVIBeADog2ENgnUA+VdRkyAarWoApAMoy2LeDICMGAEwBrAEIyAqgEkZhACd6eAB3PlcDMQB6SSl9akjYmWg1EFoAB3S9AyMJaWSoVM1teGzDGWjY+MrpeINuEFJ4BB5NAXImAGYkNBAAXzwaYNEpMwwAK3JeASERJgQ2GXg8NjxqPFhlAHkAI3H4VrwA7b2DtgwAc3g2AAUAvjYHgE90+C3CPBUACmXV9dgAJTKXQ-AD8oK+TTYABUIAw+ABXNhff4AtahGSWa4AgEYWgwL5sNGFYBXRajWBfAHAALXBEBQy2CCkDBsAZQmQUn7UhYyajKJmkDbKaisgDc8AAhMplLAAGRylEYTYy2CgtjKUiEtZ4HgApDwGUi5UK85QZrXeAotGijXLUV8DCEPgBACitB4LC+hOByOWgJxAIGAmooW5wEFGEd6QRpC98CDweUAS+UDREGUht08Aw1D45uhL3goPgSFDIRk0PgAA8-WiEcofngMC2icDCU6FMiHFE0LjnW6PV6fdm8ZlhFAAMIsEhQL4ptsyqCgkLan7AhP6iCEwNohN4WgijF3PjVp7e7Ut3NA3TABYUIVXiAAXWTKIoaGf4L7Rr4oOoSBUAMV7UM+B7KFAfA8AiDCCBgPC0rQQiuggsHIkSYq0mw9KGLAGDCGwAQQPAWqkP2Lrup6F4UH8z43ne1wyJstA0c+0qZiWwIsWwr6llmtAYFCACCbCERAOxIlaqwJph1pGsuq7rOuIKUvutCBkgKbUECMp-quIEYOa6RCt6V4Ju2lKioQXxmTiB4aZZQZ2QiXy0M2LYQE5gxkkg2rab6GA7BA1BzvaXkAPqZhuGAZjmEBOiQQgpspOYIqCMWkJOIZnPAaZojwjb0by-IUFePFina6IVliyJWV2ACyGRfOFOJOhRQ7ehqt4L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NFkX0WY2+OCASpmkFgkAAAlMwkEO5ktuTIISNwfDqBxK8owOiWS0lIDbNgLJiZfJscCEJBJvbv2xFgspRguUyt0cCmQejTEr1Mco64VF1DsDYMZJAligghT4GAS5DAogZAgKCMVEqVBYAFfQhZwhCSwvhdpD1tgvVEt8Vysi9D6HpwtPi9oogAAsWAkDOERnnXoAwhiVyYPBJQDQ66zDYKIRhUAng0qMMfHgrgLj3FUY7BhR1XCSKMPwWALokAyCgG-VwvDqD8Poc6QQiMraQFgH4kJRFQmSOxQYVkWh4HIvKEIWsiNQkQHCUgWJSV63+BmIjUgEAABepYZDOFpGADdQjJBdpbZ0LAEjQXbwAMTgNHkK0t5bK3JxkO-Y+XxnBYCwHgBwWAUB4ARpgZwKNT0OxES25w8j2EwbYYe2DiGb3lESVAZJMhf2wY3fOtgi6wkATXeQjddTZEyDQCEpEfBx3bwjZnAlOcYM9H6GBcuwwmD1WMF4UwFhLAhv6EAA)

```js
import v from "./van.js"

const {span, h1, div, img } = v.tags

const add = (base) => (elt) => v.add(base, elt)

const target = document.getElementById("app")
const title = document.getElementById("title")

const style_user_pict = `
  border:1px solid orange;
  padding: 3px;
  margin:10px`;

function User (user) {
  return (   
      // User wrapper
      div ({style:"display:flex; align-items:center;width:90%;"},
        // User picture
        div({style:"margin-right:10px"},     
          img({style:style_user_pict, src:user.picture.thumbnail})
        ),
        // User name
        div (
          span(user.name.first, " "),         
          span(user.name.last)
        )
      )
    )
}

function toJson(r) {
  return r.json()
}

function displayUsers (users) {
   add(title)(div("Random Users API")) 
   users.results.map(user => add(target)(
      User(user))
   )  
}  

fetch("https://randomuser.me/api?results=5")
  .then(toJson)
  .then(displayUsers)
  
```