DEV Community

Matias Trujillo
Matias Trujillo

Posted on

1

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 🤓)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay