DEV Community

artydev
artydev

Posted on

3

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
👋 While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay