useSearchBranches.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. "use client";
  2. import React from "react";
  3. import { getBranches } from "@/lib/frontend/apiClient";
  4. export const BRANCH_LIST_STATE = Object.freeze({
  5. IDLE: "idle",
  6. LOADING: "loading",
  7. READY: "ready",
  8. ERROR: "error",
  9. });
  10. /**
  11. * useSearchBranches
  12. *
  13. * Purpose:
  14. * - Fetch the list of branches for admin/dev users (used by the Search multi-select UI).
  15. *
  16. * UX policy:
  17. * - Fail open: if loading fails, the rest of the Search UI must still work.
  18. * - Branch users never need this list.
  19. *
  20. * @param {{ enabled: boolean }} args
  21. * @returns {{ status: "idle"|"loading"|"ready"|"error", branches: string[]|null, retry: () => void }}
  22. */
  23. export function useSearchBranches({ enabled }) {
  24. const [status, setStatus] = React.useState(
  25. enabled ? BRANCH_LIST_STATE.LOADING : BRANCH_LIST_STATE.IDLE
  26. );
  27. const [branches, setBranches] = React.useState(null);
  28. const [retryTick, setRetryTick] = React.useState(0);
  29. const retry = React.useCallback(() => {
  30. setRetryTick((n) => n + 1);
  31. }, []);
  32. React.useEffect(() => {
  33. if (!enabled) {
  34. setStatus(BRANCH_LIST_STATE.IDLE);
  35. setBranches(null);
  36. return;
  37. }
  38. let cancelled = false;
  39. setStatus(BRANCH_LIST_STATE.LOADING);
  40. setBranches(null);
  41. (async () => {
  42. try {
  43. const res = await getBranches();
  44. if (cancelled) return;
  45. const list = Array.isArray(res?.branches) ? res.branches : [];
  46. setBranches(list);
  47. setStatus(BRANCH_LIST_STATE.READY);
  48. } catch (err) {
  49. if (cancelled) return;
  50. console.error("[useSearchBranches] getBranches failed:", err);
  51. setBranches(null);
  52. setStatus(BRANCH_LIST_STATE.ERROR);
  53. }
  54. })();
  55. return () => {
  56. cancelled = true;
  57. };
  58. }, [enabled, retryTick]);
  59. return { status, branches, retry };
  60. }