Skip to main content

Read data from a cart

Note

This guide might not be compatible with features introduced in Hydrogen version 2025-05 and above. Check the latest documentation if you encounter any issues.

This guide shows you how to read a user's cart.



Anchor to Step 1: Get a visitor's cartStep 1: Get a visitor's cart

Use the cart, created from createCartHandler, to get a user's cart. You don't need to provide a cart ID because it's already handled by the cart handler. cart.get() returns a promise. Use Remix's defer so that the cart data is deferred, and streamed to the browser.

File

/app/root.jsx

export async function loader({context}) {
const {cart} = context;

return defer({
cart: cart.get(),
});
}
export async function loader({context}: LoaderArgs) {
const {cart} = context;

return defer({
cart: cart.get(),
});
}

Anchor to Step 2: Server render the content of the cartStep 2: Server render the content of the cart

You can get the content of the cart using Remix's useMatches hook, because you made it available in the root loader. Since the data is deferred, you'll need to wait for the data.

File

/app/components/CartDrawer.jsx

function CartDrawer() {
const [root] = useMatches();

// Cart data is deferred
// Use Suspense to unblock UI rendering and Await to resolve when data arrives
return (
<Suspense fallback={<CartLoading />}>
<Await resolve={root.data?.cart}>
{(cart) => <Cart cart={cart} />}
</Await>
</Suspense>
);
}
function CartDrawer() {
const [root] = useMatches();

// Cart data is deferred
// Use Suspense to unblock UI rendering and Await to resolve when data arrives
return (
<Suspense fallback={<CartLoading />}>
<Await resolve={root.data?.cart}>
{(cart) => <Cart cart={cart} />}
</Await>
</Suspense>
);
}


Was this page helpful?