Skip to Content
FrontendBundlesCRUDHooksuseTreeNeighbors

useTreeNeighbors

useTreeNeighbors fetches everything around one tree node: the root of its tree, the sibling before it, the sibling after it, and the full ancestor chain. It queries the API with nested-set range filters instead of walking client-side data, so it works on a detail page where only the current entity is loaded. Tree Position is built on it.


Import

import { useTreeNeighbors } from "@phpcreation/frontend-crud-react-nextjs-bundle/utils/hooks";

Signature

const { rootEntity, before, after, ancestors, fetching } = useTreeNeighbors( data, // the current entity, must have id, lft, rgt, lvl, root resource, // API resource name, e.g. "product_types" tenant, // tenant identifier enabled, // skip fetching until true );
type TreeNeighbor = { id: number; lvl?: number; lft?: number; rgt?: number; [key: string]: any; } | null; // returns { rootEntity: TreeNeighbor; // root of the tree (the entity itself if it is the root) before: TreeNeighbor; // previous same-level sibling, or null after: TreeNeighbor; // next same-level sibling, or null ancestors: TreeNeighbor[]; // root-to-parent chain, ordered by lft fetching: boolean; }

How it queries

All lookups are nested-set range filters on the same resource, one item each for the siblings:

ResultQuery
beforergt_range[lt]=<lft>, lvl, root, order[rgt]=desc, itemsPerPage=1
afterlft_range[gt]=<rgt>, lvl, root, order[lft]=asc, itemsPerPage=1
ancestorslft_range[lt]=<lft>, rgt_range[gt]=<rgt>, root, order[lft]=asc
rootEntitydirect fetch of <resource>/<root> (skipped when the node is the root)

Ancestors are exactly the nodes whose lft/rgt enclose the current node’s, which is the nested-set definition of “contains”.

Requests run in parallel and re-run when the entity’s id, lft, rgt, lvl, or root changes. Failures are swallowed; the neighbors just stay null.


Usage

const hasTreeFields = data?.lvl !== undefined && data?.lft !== undefined; const { rootEntity, before, after, ancestors, fetching } = useTreeNeighbors( data, resource, tenant, hasTreeFields, );

Last updated on