wip: select regency paginated

todo: search reactive

wip: paginated regency

todo: search bind

wip gess
This commit is contained in:
Khafid Prayoga
2025-10-13 13:56:41 +07:00
parent c8620e4ed2
commit bc286f16c8
4 changed files with 386 additions and 79 deletions
+81 -78
View File
@@ -1,7 +1,7 @@
import { ref, computed, watch } from 'vue'
import { refDebounced } from '@vueuse/core'
import { useDebounceFn } from '@vueuse/core'
import type { Regency } from '~/models/regency'
import type { SelectItem } from '~/components/pub/my-ui/form/select.vue'
import type { Item } from '~/components/pub/my-ui/combobox'
import type { PaginationMeta } from '~/components/pub/my-ui/pagination/pagination.type'
import { toTitleCase } from '~/lib/utils'
import * as regencyService from '~/services/regency.service'
@@ -23,9 +23,9 @@ interface CachedRegencyData {
}
// Global cache untuk regencies berdasarkan query key (province-code + search + pagination)
const regenciesCache = ref<Map<string, CachedRegencyData>>(new Map())
const loadingStates = ref<Map<string, boolean>>(new Map())
const errorStates = ref<Map<string, string | null>>(new Map())
const regenciesCache = reactive(new Map<string, CachedRegencyData>())
const loadingStates = reactive(new Map<string, boolean>())
const errorStates = reactive(new Map<string, string | null>())
interface UseRegenciesOptions {
provinceCode?: Ref<string | undefined> | string | undefined
@@ -36,18 +36,14 @@ interface UseRegenciesOptions {
export function useRegencies(options: UseRegenciesOptions | Ref<string | undefined> | string | undefined = {}) {
// Backward compatibility - jika parameter pertama adalah provinceCode
const normalizedOptions: UseRegenciesOptions = typeof options === 'object' && 'value' in options
? { provinceCode: options }
: typeof options === 'string' || options === undefined
? { provinceCode: options }
: options
const normalizedOptions: UseRegenciesOptions =
typeof options === 'object' && 'value' in options
? { provinceCode: options }
: typeof options === 'string' || options === undefined
? { provinceCode: options }
: options
const {
provinceCode,
pageSize = 10,
enablePagination = true,
enableSearch = true
} = normalizedOptions
const { provinceCode, pageSize = 10, enablePagination = true, enableSearch = true } = normalizedOptions
// Convert provinceCode ke ref jika bukan ref
const provinceCodeRef =
@@ -57,7 +53,6 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
const currentPage = ref(1)
const currentPageSize = ref(pageSize)
const searchQuery = ref('')
const debouncedSearch = refDebounced(searchQuery, 300)
// Function untuk generate query key
const generateQueryKey = (params: RegencyQueryParams) => {
@@ -66,7 +61,7 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
params.search || '',
params['page-number'] || 1,
params['page-size'] || pageSize,
params.sort || 'name:asc'
params.sort || 'name:asc',
]
return keyParts.join('|')
}
@@ -75,48 +70,50 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
const currentQueryKey = computed(() => {
return generateQueryKey({
'province-code': provinceCodeRef.value,
search: enableSearch ? debouncedSearch.value : undefined,
search: enableSearch ? searchQuery.value : undefined,
'page-number': enablePagination ? currentPage.value : undefined,
'page-size': enablePagination ? currentPageSize.value : undefined,
sort: 'name:asc'
sort: 'name:asc',
})
})
// Computed untuk mendapatkan regencies berdasarkan current query
const regencies = computed(() => {
const queryKey = currentQueryKey.value
const cachedData = regenciesCache.value.get(queryKey)
const cachedData = regenciesCache.get(queryKey)
return cachedData?.data || []
})
// Computed untuk pagination meta
const paginationMeta = computed(() => {
const queryKey = currentQueryKey.value
const cachedData = regenciesCache.value.get(queryKey)
return cachedData?.meta || {
recordCount: 0,
page: currentPage.value,
pageSize: currentPageSize.value,
totalPage: 0,
hasNext: false,
hasPrev: false,
}
const cachedData = regenciesCache.get(queryKey)
return (
cachedData?.meta || {
recordCount: 0,
page: currentPage.value,
pageSize: currentPageSize.value,
totalPage: 0,
hasNext: false,
hasPrev: false,
}
)
})
// Computed untuk loading state
const isLoading = computed(() => {
const queryKey = currentQueryKey.value
return loadingStates.value.get(queryKey) || false
return loadingStates.get(queryKey) || false
})
// Computed untuk error state
const error = computed(() => {
const queryKey = currentQueryKey.value
return errorStates.value.get(queryKey) || null
return errorStates.get(queryKey) || null
})
// Computed untuk format SelectItem
const regencyOptions = computed<SelectItem[]>(() => {
// Computed untuk format Item
const regencyOptions = computed<Item[]>(() => {
return regencies.value.map((regency) => ({
label: toTitleCase(regency.name),
value: regency.code,
@@ -128,29 +125,29 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
async function fetchRegencies(params?: Partial<RegencyQueryParams>, forceRefresh = false) {
const queryParams: RegencyQueryParams = {
'province-code': params?.['province-code'] || provinceCodeRef.value,
search: enableSearch ? (params?.search || debouncedSearch.value) : undefined,
'page-number': enablePagination ? (params?.['page-number'] || currentPage.value) : undefined,
'page-size': enablePagination ? (params?.['page-size'] || currentPageSize.value) : undefined,
sort: params?.sort || 'name:asc'
search: enableSearch ? params?.search || searchQuery.value : undefined,
'page-number': enablePagination ? params?.['page-number'] || currentPage.value : undefined,
'page-size': enablePagination ? params?.['page-size'] || currentPageSize.value : undefined,
sort: params?.sort || 'name:asc',
}
// Jika tidak ada province code, return
if (!queryParams['province-code']) return
// if (!queryParams['province-code']) return // buat komponen select birth
const queryKey = generateQueryKey(queryParams)
// Jika tidak force refresh dan sudah ada cache, skip
if (!forceRefresh && regenciesCache.value.has(queryKey)) {
if (!forceRefresh && regenciesCache.has(queryKey)) {
return
}
// Jika sedang loading, skip untuk mencegah duplicate calls
if (loadingStates.value.get(queryKey)) {
if (loadingStates.get(queryKey)) {
return
}
loadingStates.value.set(queryKey, true)
errorStates.value.set(queryKey, null)
loadingStates.set(queryKey, true)
errorStates.set(queryKey, null)
try {
// Prepare API parameters
@@ -183,9 +180,10 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
recordCount: meta.record_totalCount,
page: queryParams['page-number'] || 1,
pageSize: queryParams['page-size'] || regenciesData.length,
totalPage: enablePagination && queryParams['page-size']
? Math.ceil(meta.record_totalCount / queryParams['page-size'])
: 1,
totalPage:
enablePagination && queryParams['page-size']
? Math.ceil(meta.record_totalCount / queryParams['page-size'])
: 1,
hasNext: false,
hasPrev: false,
}
@@ -196,27 +194,27 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
}
// Cache the result
regenciesCache.value.set(queryKey, {
data: regenciesData,
meta: paginationMeta,
queryKey
regenciesCache.set(queryKey, {
data: [...regenciesData],
meta: { ...paginationMeta },
queryKey,
})
} else {
errorStates.value.set(queryKey, 'Gagal memuat data kabupaten/kota')
errorStates.set(queryKey, 'Gagal memuat data kabupaten/kota')
console.error('Failed to fetch regencies:', response)
}
} catch (err) {
errorStates.value.set(queryKey, 'Terjadi kesalahan saat memuat data kabupaten/kota')
errorStates.set(queryKey, 'Terjadi kesalahan saat memuat data kabupaten/kota')
console.error('Error fetching regencies:', err)
} finally {
loadingStates.value.set(queryKey, false)
loadingStates.set(queryKey, false)
}
}
// Function untuk mencari regency berdasarkan code (search di semua cached data)
function getRegencyByCode(code: string): Regency | undefined {
// Search di semua cached data
for (const cachedData of regenciesCache.value.values()) {
for (const cachedData of regenciesCache.values()) {
const found = cachedData.data.find((regency) => regency.code === code)
if (found) return found
}
@@ -226,7 +224,7 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
// Function untuk mencari regency berdasarkan name (search di semua cached data)
function getRegencyByName(name: string): Regency | undefined {
// Search di semua cached data
for (const cachedData of regenciesCache.value.values()) {
for (const cachedData of regenciesCache.values()) {
const found = cachedData.data.find((regency) => regency.name.toLowerCase() === name.toLowerCase())
if (found) return found
}
@@ -274,24 +272,24 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
if (code) {
// Clear semua cache yang mengandung province code tersebut
const keysToDelete: string[] = []
for (const [key] of regenciesCache.value.entries()) {
for (const [key] of regenciesCache.entries()) {
if (key.startsWith(code + '|')) {
keysToDelete.push(key)
}
}
keysToDelete.forEach(key => {
regenciesCache.value.delete(key)
loadingStates.value.delete(key)
errorStates.value.delete(key)
keysToDelete.forEach((key) => {
regenciesCache.delete(key)
loadingStates.delete(key)
errorStates.delete(key)
})
}
}
// Function untuk clear semua cache
function clearAllCache() {
regenciesCache.value.clear()
loadingStates.value.clear()
errorStates.value.clear()
regenciesCache.clear()
loadingStates.clear()
errorStates.clear()
}
// Function untuk refresh data
@@ -318,25 +316,30 @@ export function useRegencies(options: UseRegenciesOptions | Ref<string | undefin
{ immediate: true },
)
// Watch perubahan search query untuk auto fetch
watch(
debouncedSearch,
(newSearch, oldSearch) => {
if (enableSearch && newSearch !== oldSearch) {
fetchRegencies()
}
const triggerFetchAfterIdle = useDebounceFn(() => {
if (enableSearch) {
currentPage.value = 1
fetchRegencies()
}
)
}, 1000)
// Watch perubahan search query untuk auto fetch dan reset halaman
watch(searchQuery, (newSearch, oldSearch) => {
if (newSearch !== oldSearch) {
triggerFetchAfterIdle()
}
})
// Watch perubahan pagination untuk auto fetch
watch(
[currentPage, currentPageSize],
() => {
if (enablePagination) {
fetchRegencies()
}
watch([currentPage, currentPageSize], () => {
if (enablePagination) {
fetchRegencies()
}
)
})
watch(regencyOptions, (val) => {
console.log('[regencyOptions] updated', val.length)
})
return {
// Data