DEV Community

artydev
artydev

Posted on

VanJS 1.0 has landed !!!

The little library that can, has reached the 1.0 release, thanks to TAO :-)
Among the new features, there is the awaited 'derived' state, and the simplification of state binding for complex objects.

Here is the 1.0 version of the new way of binding complex objects:
Demo

import { van } from "./van.js"

const { div, br, ul, li } = van.tags,
  data = van.state({ status: "Unfetched" }),
  url = "https://randomuser.me/api?results=5";

const ResponseOk = 200;

const InfoStatus = {
  "Fetching Users" : {msg: "Fetching users", style: "color: red; font-size:24px" }, 
  "Users Fetched" : {msg: "Users fetched", style: "color: green; font-size:24px" }, 
  "Unfetched" : {msg: "Will fetch users within 2s", style: "color: blue; font-size:24px" }, 
  "Error" : {msg: "An error occured", style: "color: blue; font-size:24px" }, 
}

const styleUser = "font-size:24px";

function UserList(user) {
  return (
    ul (
      li ( {style:styleUser} , user.name.first)    
  ))
}

function sleep (ms) {
  return new Promise ((res) => {
    setTimeout(res, ms)
  })
}

function setErrorData () {
    data.val = { status: "Error", jsonResult : [] }   
}

const fetchData = async () => {
  data.val = { status: "Fetching Users" };
  let response = {};
  try {
     response  =  await fetch(url)
  }
  catch (err) {
    setErrorData ()
  }
  if (ResponseOk) {  
    const jsonResult = await response.json()
    data.val = { status: "Users Fetched", jsonResult }                       
  }
  else {
    setErrorData ()  
  }
}

function App () {
  const view =  () => {  
    const 
      users = data.val.jsonResult?.results ?? [],
      info = InfoStatus[data.val.status];
    return div (
      div ({style: info.style}, info.msg, br()),       
      users.map (UserList)  
    ) 
  }
  return view
}

van.add (document.body, App () )

sleep(2000).then(fetchData)     
Enter fullscreen mode Exit fullscreen mode

Top comments (0)