Files
sorvor-back/components/LocationSelector/index.tsx
Thanu Poptiphueng c1a019a461
All checks were successful
backend-action / build-image (push) Successful in 1m9s
lint
2024-05-16 17:26:27 +07:00

89 lines
2.4 KiB
TypeScript

"use client";
import { useContext, useEffect, useState } from "react";
import { LocationContext } from "../locationContext";
type Props = {
provinces: Province[];
};
type Province = {
id: number;
name: string;
zones: Zone[];
};
type Zone = {
id: number;
name: string;
province: number;
};
export default function LocationSelector({ provinces }: Props) {
const [provinceId, setProvinceId] = useState<number | undefined>(undefined);
const [amphurList, setAmphurList] = useState<Zone[] | undefined>(undefined);
const [amphurId, setAmphurId] = useState<number | undefined>(undefined);
const locationContext = useContext(LocationContext);
function setProvince(_id: string) {
const id = parseInt(_id);
setProvinceId(id);
const province = provinces.find((p) => p.id == id);
if (province == undefined) return;
setAmphurList(province.zones);
setAmphurId(undefined);
}
function setAmphur(_id: string) {
const id = parseInt(_id);
setAmphurId(id);
}
useEffect(() => {
if (locationContext == undefined) return;
if (amphurId == undefined || provinceId == undefined) {
locationContext.zone[1](undefined);
locationContext.province[1](undefined);
return;
}
locationContext.zone[1](amphurId);
locationContext.province[1](provinceId);
}, [amphurId, locationContext, provinceId]);
return (
<div className="flex flex-col gap-2">
<div className="flex gap-2">
:
<select
value={provinceId}
className="flex-1"
onChange={(e) => setProvince(e.currentTarget.value)}
>
<option value={undefined} hidden>
None
</option>
{provinces.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
</div>
{amphurList && (
<div className="flex gap-2">
:
<select
value={amphurId}
className="flex-1"
onChange={(e) => setAmphur(e.currentTarget.value)}
>
<option value={undefined} hidden>
None
</option>
{amphurList.map((a) => (
<option key={a.id} value={a.id}>
{a.name}
</option>
))}
</select>
</div>
)}
</div>
);
}