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> )}Select only what we need to display the address content
import { useSelection } from "@frend-digital/centra/client";
export const useSelectionAddress = () => { return useSelection({ select: (data) => ({ address: data?.selection?.address, }), });};Use it to set default address values if they are saved on a selection
"use client";
import { useSelectionAddress } from "./hooks";import { omitFalsy } from "@frend-digital/utils";import { useAddress } from "@frend-digital/checkout/address"
const AddressForm = () => { const { form } = useAddress(); const { data: address, isLoading } = useSelectionAddress()
useEffect(() => { if(isLoading || !address) return; const parsed = omitFalsy(address); // Filter only the truthy address values
Object.entires(parsed).forEach(([key, value]) => { form.resetField(key, value) // Set each value e.g. firstName to the selection value })
}, [address, isLoading]);
return ( <form> {/* This will now show the firstName prefilled */} <input {form.register("firstName")} /> </form> )};…
Anatomy
interface UseSelectionOptions<T = any> { select?: (data: any) => T;}
export declare function useSelection<T = any>( options?: UseSelectionOptions<T>): UseSelectionResult<T>;