Files
meditation-admin/lib/useResource.ts
T
2026-06-03 03:08:57 +03:30

88 lines
2.3 KiB
TypeScript

"use client";
import { useCallback, useEffect, useState } from "react";
import { ApiError, apiFetch, unwrap } from "./api";
type Query = Record<string, string | number | boolean | undefined | null>;
// Generic GET-list hook. Unwraps `{ data: [...] }` and tolerates either a bare
// array or a paginated object with a `data` field.
export function useList<T = unknown>(
path: string | null,
query?: Query,
): {
data: T[];
loading: boolean;
error: string | null;
reload: () => void;
} {
const [data, setData] = useState<T[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const queryKey = JSON.stringify(query ?? {});
const reload = useCallback(() => {
if (!path) {
// No path yet (e.g. a filter not chosen): show an empty, non-loading state.
setData([]);
setLoading(false);
setError(null);
return;
}
setLoading(true);
setError(null);
apiFetch(path, { query })
.then((res) => {
const value = unwrap<unknown>(res);
setData(Array.isArray(value) ? (value as T[]) : []);
})
.catch((e: unknown) => {
setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات");
setData([]);
})
.finally(() => setLoading(false));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [path, queryKey]);
useEffect(() => {
reload();
}, [reload]);
return { data, loading, error, reload };
}
// Single-record GET hook.
export function useItem<T = unknown>(path: string | null): {
data: T | null;
loading: boolean;
error: string | null;
reload: () => void;
} {
const [data, setData] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
if (!path) {
setData(null);
setLoading(false);
setError(null);
return;
}
setLoading(true);
setError(null);
apiFetch(path)
.then((res) => setData(unwrap<T>(res)))
.catch((e: unknown) =>
setError(e instanceof ApiError ? e.message : "خطا در دریافت اطلاعات"),
)
.finally(() => setLoading(false));
}, [path]);
useEffect(() => {
reload();
}, [reload]);
return { data, loading, error, reload };
}