Built-in Utilities
Fetchers

Fetchers

Fetchers are data fetching components. They are components that render view and fetch data for necessary operations. They're reusable and composable.

  • Data fetching component with an arrow function
const Users = (props) => {
  return`
    <div id="users">
      <ul id="#componentId" data-prepend="#componentId">
        <li>Item 1</li>
      </ul>
      // the rest of the component
    </div>
  `
};
  • Data fetching component with a native function
function Users (props) {
 
  return`
    <div id="users">
      <ul id="#componentId" data-prepend="#componentId">
        <li>Item 1</li>
      </ul>
      // the rest of the component
    </div>
  `
};

Data fetching attributes

There are three attributes and you have to use one of them whenever you use a data fetching component. They are:

  1. data-replace
<ul id="componentId" data-replace="#componentId">
  <li>Item 1</li>
</ul>

data-replace="#componentId" means an update version is set to replace the element with id #componentId. data-replace should be added to a data fetching component to replace an element with an updated version.

  1. data-append
<ul id="componentId" data-append="#componentId">
  <li>Item 1</li>
</ul>

data-append="#componentId" means more items should be appended to the element with id #componentId. data-append should be added to a data fetching component to append more items.

  1. data-prepend
<ul id="#componentId" data-prepend="#componentId">
  <li>Item 1</li>
</ul>

data-prepend="#componentId" means more items should be prepended to an element with id #componentId. data-prepend should be added to a data fetching component to prepend more items.

  • Working example of a fetcher
const Users = async () => {
  const response = await fetch("https://randomuser.me/api?results=30");
  const users = await response.json();
   
  return `
      <div id="users" data-replace="#list">
        <h1 class="text-3xl">User list</h1>
        <Counter />
        <ul class="list" id="list">
          ${users.results.map((user) => {
            return `
                <li class="item">
                  <img src="${user.picture.medium}">
                  <p class="name">${user.name.first}</p>
                </li>
              `;
          })}
          </ul>
          <button 
            class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mb-5"
            onClick="$render(Users)">Load more users...</button>
      </div>
    `;
};

Calling a fetcher

  • Use a fetcher as a component

Without props

<Users />
 
or
 
$render(Users)

With props

//Dynamically
<Users users=${stringify(users)} />
or
$render(Users, ${stringify(users)})
 
 
//Statically
<Users users="[{}, {}, {}]" />
or
$render(Users, [{}, {}, {}])
 
// Use as as event handler
<button onClick="$render(Users, '${stringify(users)}'">
  Load users
</button>
  • Playground