Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ export function getObjectKeys<T extends object>(obj: T): (keyof T)[] {
return Object.keys(obj) as (keyof T)[]
}

export function objectFromEntries<K extends string | number | symbol, V>(
entries: [K, V][],
): Record<K, V> {
return Object.fromEntries(entries) as Record<K, V>
}

export function getAreaRelations(area: Area) {
return {
parent: parentArea[area],
Expand Down
40 changes: 33 additions & 7 deletions modules/MapDashboard/AreaSelectors.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@

import { type FeatureArea, config, featureConfig } from '@/lib/config'
import type { Query } from '@/lib/data'
import { debounce, getAreaRelations, getObjectKeys } from '@/lib/utils'
import {
debounce,
getAreaRelations,
getObjectKeys,
objectFromEntries,
} from '@/lib/utils'
import { useMemo, useState } from 'react'
import ComboboxArea from './ComboboxArea'
import { useMapDashboard } from './hooks/useDashboard'
Expand All @@ -11,12 +16,7 @@ const MAX_PAGE_SIZE = config.dataSource.area.pagination.maxPageSize

export default function AreaSelectors() {
const { isLoading, selectedArea, changeSelectedArea } = useMapDashboard()
const [query, setQuery] = useState<{ [A in FeatureArea]: Query<A> }>({
province: {},
regency: { parentCode: selectedArea.province?.code },
district: { parentCode: selectedArea.regency?.code },
village: { parentCode: selectedArea.district?.code },
})

const areas = useMemo(
() =>
getObjectKeys(featureConfig).map((area) => ({
Expand All @@ -26,6 +26,32 @@ export default function AreaSelectors() {
[],
)

const defaultQuery = objectFromEntries(
areas.reduce<[FeatureArea, Query<FeatureArea>][]>(
(acc, { area, parent }) => {
let query: Query<typeof area> = {}

if (area === 'province') {
query = { limit: MAX_PAGE_SIZE }
}

if (parent && parent !== 'island' && selectedArea[parent]) {
query = {
parentCode: selectedArea[parent]?.code, // Need optional chaining. Build fails without it
limit: MAX_PAGE_SIZE,
}
}

acc.push([area, query])
return acc
},
[],
),
)

const [query, setQuery] =
useState<{ [A in FeatureArea]: Query<A> }>(defaultQuery)

return (
<div className="flex flex-col gap-2 w-full">
{areas.map(({ area, parent, child }) => (
Expand Down