Reading the Users Atom

Avatar of Hemanta SundarayHemanta Sundaray

We’ve created the usersAtom. Now, let’s read its value in the UserGrid component.

To read an atom’s value, we use the useAtomValue hook.

Replace the code inside components/user-grid.tsx with the following:

components/user-grid.tsx
"use client";
import { useAtomValue } from "@effect-atom/atom-react";
import { usersAtom } from "@/atoms/user";
export function UserGrid() {
const usersResult = useAtomValue(usersAtom);
console.log("Users Result: ", usersResult);
return (
<pre className="bg-white border p-4">
{JSON.stringify(usersResult, null, 2)}
</pre>
);
}

The value returned by useAtomValue(usersAtom) is a Result type, which can be in one of the following three states:

  • Initial: Data fetching hasn’t completed yet
  • Success: Data fetching succeeded with a value
  • Failure: Data fetching failed with an error

Let’s observe these states in action.

Make sure your app is running, then visit localhost:3000. Open the browser console. You’ll see usersResult logged multiple times. Some in the Initial state (_tag: "Initial") and some in the Success state (_tag: "Success"). The Success state is also visible on the page as JSON.

To see the Failure state, go to user-service.ts and change the endpoint from /users to /usersx (which doesn’t exist). Visit the home page again. You’ll see the Failure state (_tag: "Failure") on both the page and in the browser console.

Note
Remember to revert the endpoint back to /users before continuing.

Sign in to save progress

Stay in the loop

Get notified when new chapters are added and when this course is complete.