| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- "use client";
- import React from "react";
- import { getBranches } from "@/lib/frontend/apiClient";
- export const BRANCH_LIST_STATE = Object.freeze({
- IDLE: "idle",
- LOADING: "loading",
- READY: "ready",
- ERROR: "error",
- });
- /**
- * useSearchBranches
- *
- * Purpose:
- * - Fetch the list of branches for admin/dev users (used by the Search multi-select UI).
- *
- * UX policy:
- * - Fail open: if loading fails, the rest of the Search UI must still work.
- * - Branch users never need this list.
- *
- * @param {{ enabled: boolean }} args
- * @returns {{ status: "idle"|"loading"|"ready"|"error", branches: string[]|null, retry: () => void }}
- */
- export function useSearchBranches({ enabled }) {
- const [status, setStatus] = React.useState(
- enabled ? BRANCH_LIST_STATE.LOADING : BRANCH_LIST_STATE.IDLE
- );
- const [branches, setBranches] = React.useState(null);
- const [retryTick, setRetryTick] = React.useState(0);
- const retry = React.useCallback(() => {
- setRetryTick((n) => n + 1);
- }, []);
- React.useEffect(() => {
- if (!enabled) {
- setStatus(BRANCH_LIST_STATE.IDLE);
- setBranches(null);
- return;
- }
- let cancelled = false;
- setStatus(BRANCH_LIST_STATE.LOADING);
- setBranches(null);
- (async () => {
- try {
- const res = await getBranches();
- if (cancelled) return;
- const list = Array.isArray(res?.branches) ? res.branches : [];
- setBranches(list);
- setStatus(BRANCH_LIST_STATE.READY);
- } catch (err) {
- if (cancelled) return;
- console.error("[useSearchBranches] getBranches failed:", err);
- setBranches(null);
- setStatus(BRANCH_LIST_STATE.ERROR);
- }
- })();
- return () => {
- cancelled = true;
- };
- }, [enabled, retryTick]);
- return { status, branches, retry };
- }
|