Skip to content

useSelection

The useSelection hook is used to fetch the current user cart and address information from Centra.

Usage

Basic Usage

"use client";
import { useSelection } from "@frend-digital/centra/client";
const ReturnEverything = () => {
const { data: selection, isLoading } = useSelection();
if (isLoading) {
return <div>Loading...</div>;
}
return <div>{JSON.stringify(selection, null, 2)}</div>;
};

Selecting only what you need - Slices

The useSelection hook is using React Query under the hook, which means we can pass a select function to only select the values that we need, and only re-render the component when that piece of data changes. This way you can make reusable hooks for any action needing a selection:

Select only what we need to display the cart content

import { useSelection } from "@frend-digital/centra/client";
export const useCart = () => {
return useSelection({
select: (data) => ({
total: data?.selection?.totals.grandTotalPrice || "",
items: data?.selection?.items.filter(Boolean),
}),
});
};

Use it in a component

"use client";
import { useCart } from "./hooks"
const CartContent = () => {
const {data: cart, isLoading} = useCart();
return (
<section>
<h2>Cart</h2>
<ul>
{!isLoading && cart.items?.map((item) => (
<li key={item.line}>
<h3>{item.product?.name}</h3>
<p>{item.quantity}</p>
</li>
))}
{isLoading && <>
<CartItemSkeleton />
<CartItemSkeleton />
</>}
<footer>
<h3>Total</h3>
<p>{cart.total}</p>
</footer>
</section>
)
}

Anatomy

interface UseSelectionOptions<T = any> {
select?: (data: any) => T;
}
export declare function useSelection<T = any>(
options?: UseSelectionOptions<T>
): UseSelectionResult<T>;