DEV Community

Matias Trujillo
Matias Trujillo

Posted on

How to consume promises with webcomponents? 🤓

Atomico brings the functional syntax of React to web components to make things simpler, today I would like to show you solving how to consume promise in just 3 steps.

Step 1

import the useAsync hook from Atomico.

import { useAsync } from "atomico";
Enter fullscreen mode Exit fullscreen mode

Step 2

Abstract your promise into a callback.

const getUsers = () => fetch("/api/users").then((res) => res.json());
Enter fullscreen mode Exit fullscreen mode

Step 3

Finally in your webcomponent created with Atomico add the useAsync hook and consume the promise.

function myComponent() {
  const users = usyAsync(getUsers);

  return (
    <host>
      <h1>Users({users.length})</h1>
      <ul>
        {users.map((user) => (
          <li>{user.name}</li>
        ))}
      </ul>
    </host>
  );
}
Enter fullscreen mode Exit fullscreen mode

And that's it 🎉, you are already consuming promises with Atomico, remember that this way does not allow us to observe the resolution status, since with the useAsync hook we seek to delegate that process to a parent component (This is known as suspense 🤓)

Top comments (0)