DEV Community

artydev
artydev

Posted on

VanJS : Showing status while fetching data

Tao showed a nice tips while loading data: Demo

How could this be simpler ?

Look Ma, no hooks :-)

const data = van.state({ status: "Unfetched" })

const fetchData = async () => {
  data.val = { status: "Fetching Users" }
  const jsonResult = await (await fetch(url)).json()
  data.val = { status: "Users Fetched", jsonResult }    
}
Enter fullscreen mode Exit fullscreen mode

Here is the complete code :

import van from "https://vanjs.org/code/van-0.11.9.min.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 view () {
  return van.bind (data, () => {  
    const 
      users = data.val.jsonResult?.results ?? [],
      info = InfoStatus[data.val.status];
    return div (
      div ({style: info.style}, info.msg, br()),       
      users.map (UserList)  
    ) 
  })
}

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

sleep(2000).then(fetchData)     


Enter fullscreen mode Exit fullscreen mode

Top comments (0)