36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
import { useDebouncedValue } from "@mantine/hooks";
|
|
import { useSearchParams } from "react-router";
|
|
import { useBondSearch } from "@/entities/bond";
|
|
import { apiErrorCode } from "@/shared/api";
|
|
import { instrumentLogoUrl } from "@/shared/lib";
|
|
|
|
const SEARCH_DEBOUNCE_MS = 300;
|
|
|
|
function useBondsPageVm() {
|
|
const [params, setParams] = useSearchParams();
|
|
const query = params.get("q") ?? "";
|
|
const [debounced] = useDebouncedValue(query.trim(), SEARCH_DEBOUNCE_MS);
|
|
const result = useBondSearch(debounced);
|
|
const waiting = query.trim() !== debounced;
|
|
return {
|
|
query,
|
|
setQuery: (q: string) => setParams(q ? { q } : {}, { replace: true }),
|
|
loading: query.trim().length >= 2 && (waiting || result.isLoading),
|
|
error: result.isError,
|
|
code: apiErrorCode(result.error),
|
|
retry: () => {
|
|
void result.refetch();
|
|
},
|
|
ready: debounced.length >= 2 && !waiting && Boolean(result.data),
|
|
items:
|
|
result.data?.map((bond) => ({
|
|
...bond,
|
|
to: `/bonds/${encodeURIComponent(bond.slug ?? bond.instrumentUid)}`,
|
|
logoSrc: instrumentLogoUrl(bond.logoName),
|
|
})) ?? [],
|
|
};
|
|
}
|
|
type BondsPageVm = ReturnType<typeof useBondsPageVm>;
|
|
|
|
export { type BondsPageVm, useBondsPageVm };
|