VanJS : Showing status while fetching data
Tags: vanjs, javascript, webdev
Published: 2023-07-02 18:20:18

Tao showed a nice tips while loading data: [Demo](https://flems.io/#0=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAGhAGMB7NYmBvEAXwvW10QICsEqdBk2J4IWAA60ATsQAEANwxo5YabSxyAOiBLEJcRAHojStP3wyA5kboATGKeUBaAAz4AjB-wBOfFgg0fH4dLTQwoTh5YDk7CAUKOQAjaUSAVyhEqAg5VjkAXkVlfGIMKzgKMLlYjFKCoqCo2pgAChim4jTDbRAAVTQwGGJqQhg7HVyASkqVOTTpKHqdPQNjI2llOw0umGl-RwwJCAB+aXgM4jh8gFYdAG4wiPoouQAleCk0OBgAeQBreoAJlcrge4TQkXkAEkBrQAMqlTpwerAKo9ABiQxGgSscl632kcAmiDkwCwcCsJJ0mOGhBxcwJRMociiAE9YFSaLQoDISWc7HdVPRiM44BAAF4wRCAgAsEgAHhN2NpZjp8btkTSRmNiaTyZSeurCaosaNxsy2RyenQedISVYzkxBWBhaKJVLZQqlYk0WqBqadSA5CSyRTOQB1aCLQa0hkauQAdwgxDpKkBTMSlql1u5vOSUDSMGdrrFkulcsVQeVvpAAFFpOppLrQwadABBFS7RtyWjUajzQOZ4js7M6G15pIFotChhusueyu5H1oViPCHPeRZo1LcAl93lr0gMFhMBpCHECD0PEEgAyECiLR20kmpLRZ060hULTR1Qycm-szVNU2T-qSWaIFuBJ5OkBL4JgOD4JAhLEC+QFopMkxhKu4Knuel4qHAsAwBI-7ki+qKzO+8wqGgMAJnIAAK6gBN8-4tGccAvvkAB8r6ASyQwACriDAtBpMQ7HwIkZFoqwmErmuuHUBeV7fMQ9aNgAIrUGD-uRP41KU+BKIshTtIiXSchpMg6Ik-D0O8cAXMGcjIAAurkaEKSoTxfPIMYjNpdSFBgcCshCekFLxFHVHYOnGRgpmkiyFndNSpr0kaTK5GCwFDHIHGfKxZmsLlcjENIrJ8UB1SFc8MDVIUcgYAmGDJiatKPgs8nVNh1TULUIz-l2+n8Wp1nSEFuktD1uRohAYD-o5RW-H85HVAZkJyPZaCOc5IWte1dVfDAwRwPQM0GXFRkmSiKW1JZhqMnIWpmrZ23nbt5xQPIeQ1f9AOA7JaIwFArExUB40NjIU2RSqvVYWuJ5nsp+GKBAdGRRDVGfg0+BJIEdj-tdGCJDNUXJfDQFbQZv7PYUJMJVAZ0Od9xDHPgHEXMixzHK5bkzADgQuvUMIugiD1wMgjMmfgHRdG5ZW1UM1GxPE-602rCj-sA4FyMLtBy8OsDKgb-gUokKQzdMQP8XTGr+Ic-5GneUSoQZL6yfJ2FhGY+AYHYRMtFs-Y4Aw+O0HYrKJAoGP0eT8lhIRMDES0wIgpMJSjGgLQBYQU2oV5YSUCA3ywKjzx4AAbD4iCuG4ddsBwIDwdwBDUHAAhcsIzA8GwAst1weAALIAGq9KPygAFJwmwQA)

How could this be simpler ?

Look Ma, no hooks :-)

```js
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 }    
}
```


Here is the complete code :


```js
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)     

     
```