import { useCallback } from 'react';
import { SearchResponse, DocType } from '../types';
import { useApi, buildUrl } from './useApi';
const PAGE_SIZE = 20;
export function useBrowse() {
const { data, loading, error, fetchData } = useApi<SearchResponse>();
const browse = useCallback(async (
type: DocType = 'all',
offset: number = 0
) => {
const url = buildUrl('/list', {
type,
limit: PAGE_SIZE,
offset,
});
return fetchData(url);
}, [fetchData]);
const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 0;
const currentPage = data ? Math.floor(data.offset / PAGE_SIZE) + 1 : 0;
const hasPrev = data ? data.offset > 0 : false;
const hasNext = data ? data.offset + PAGE_SIZE < data.total : false;
return {
results: data?.results ?? [],
total: data?.total ?? 0,
offset: data?.offset ?? 0,
loading,
error,
browse,
pagination: {
totalPages,
currentPage,
hasPrev,
hasNext,
pageSize: PAGE_SIZE,
},
};
}