added location element
All checks were successful
backend-action / build-image (push) Successful in 1m50s

This commit is contained in:
2024-05-16 12:50:14 +07:00
parent 6d6bef8f50
commit 05f3e019a8
4 changed files with 135 additions and 21 deletions

View File

@@ -0,0 +1,76 @@
"use client";
import { useContext, useEffect, useState } from "react";
import { LocationContext } from "../locationContenxt";
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) {
let [provinceId, setProvinceId] = useState<number | undefined>(undefined);
let [amphurList, setAmphurList] = useState<Zone[] | undefined>(undefined);
let [amphurId, setAmphurId] = useState<number | undefined>(undefined);
const locationContext = useContext(LocationContext);
function setProvince(_id: string) {
let id = parseInt(_id);
setProvinceId(id);
let province = provinces.find((p) => p.id == id);
if (province == undefined) return;
setAmphurList(province.zones);
setAmphurId(undefined);
}
function setAmphur(_id: string) {
let 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]);
return (
<div className="flex flex-col gap-2">
<select
value={provinceId}
onChange={(e) => setProvince(e.currentTarget.value)}
>
<option value={undefined}>None</option>
{provinces.map((p) => (
<option key={p.id} value={p.id}>
{p.name}
</option>
))}
</select>
{amphurList && (
<select
value={amphurId}
onChange={(e) => setAmphur(e.currentTarget.value)}
>
<option value={undefined}>None</option>
{amphurList.map((a) => (
<option key={a.id} value={a.id}>
{a.name}
</option>
))}
</select>
)}
</div>
);
}

View File

@@ -0,0 +1,32 @@
"use client";
import {
Dispatch,
ReactNode,
SetStateAction,
createContext,
useState,
} from "react";
type LocationContextType = {
zone: [number | undefined, Dispatch<SetStateAction<number | undefined>>];
province: [number | undefined, Dispatch<SetStateAction<number | undefined>>];
};
export const LocationContext = createContext<LocationContextType | undefined>(
undefined
);
export default function LocationContextProvider({
children,
}: {
children?: ReactNode;
}) {
let zone = useState<number | undefined>(undefined);
let province = useState<number | undefined>(undefined);
return (
<LocationContext.Provider value={{ zone, province }}>
{children}
</LocationContext.Provider>
);
}