Files
pokemon-inventory/apps/web/src/composables/useCatalogSearch.js
T

38 lines
1.1 KiB
JavaScript

import { ref, watch } from 'vue';
import { searchCatalog } from '@/services/catalog-service.js';
export function useCatalogSearch({ initialQuery = '', initialPage = 1 } = {}) {
const query = ref(initialQuery);
const page = ref(initialPage);
const result = ref({ items: [], pagination: { page: 1, limit: 20, total: 0, totalPages: 0 } });
const isLoading = ref(false);
const error = ref(null);
let requestId = 0;
async function load() {
const currentRequestId = ++requestId;
isLoading.value = true;
error.value = null;
try {
const nextResult = await searchCatalog({ query: query.value, page: page.value });
if (currentRequestId === requestId) result.value = nextResult;
} catch (requestError) {
if (currentRequestId === requestId) error.value = requestError;
} finally {
if (currentRequestId === requestId) isLoading.value = false;
}
}
watch(query, load);
watch(page, load);
function goToPage(nextPage) {
if (nextPage >= 1 && nextPage <= result.value.pagination.totalPages) {
page.value = nextPage;
}
}
return { query, page, result, isLoading, error, load, goToPage };
}