diff --git a/src/components/FormElements/select.tsx b/src/components/FormElements/select.tsx index f3a3ddc..374c891 100644 --- a/src/components/FormElements/select.tsx +++ b/src/components/FormElements/select.tsx @@ -3,7 +3,7 @@ import { ChevronUpIcon } from "@/assets/icons"; import { cn } from "@/lib/utils"; import { ILabelValue } from "@/types/shared"; -import { useId, useState, type ChangeEvent } from "react"; +import { useEffect, useId, useState, type ChangeEvent } from "react"; import { type FieldErrors, type FieldValues, @@ -24,8 +24,9 @@ type PropsType = { required?: boolean; clearable?: boolean; onClear?: () => void; + value?: string; } & ( - | { placeholder?: string; defaultValue: string } + | { placeholder?: string; defaultValue?: string } | { placeholder: string; defaultValue?: string } ) & Partial; @@ -46,6 +47,7 @@ export function Select({ ref, clearable = false, onClear, + value: controlledValue, ...props }: PropsType) { const id = useId(); @@ -54,10 +56,23 @@ export function Select({ const [value, setValue] = useState(defaultValue || ""); const error = errors && errors[name]; + useEffect(() => { + if (controlledValue !== undefined) { + setValue(controlledValue); + setIsOptionSelected(!!controlledValue); + } + }, [controlledValue]); + const handleClear = () => { setValue(""); setIsOptionSelected(false); onClear?.(); + if (onChange) { + const event = { + target: { value: "" }, + } as ChangeEvent; + onChange(event); + } }; return ( @@ -83,7 +98,9 @@ export function Select({ ref={ref} value={value} onChange={(e) => { - setValue(e.target.value); + if (controlledValue === undefined) { + setValue(e.target.value); + } setIsOptionSelected(!!e.target.value); onChange?.(e); }} diff --git a/src/components/Tables/admins/AdminListFilters.tsx b/src/components/Tables/admins/AdminListFilters.tsx index c871356..010af20 100644 --- a/src/components/Tables/admins/AdminListFilters.tsx +++ b/src/components/Tables/admins/AdminListFilters.tsx @@ -1,11 +1,13 @@ import InputGroup from "@/components/FormElements/InputGroup"; import { Select } from "@/components/FormElements/select"; -import { AdminRoles, AdminStatus } from "@/constants/enums"; +import { AdminStatus } from "@/constants/enums"; import { getEnumAsArray } from "@/utils/shared"; import { FieldValues, UseFormHandleSubmit, UseFormRegister, + UseFormSetValue, + UseFormWatch, } from "react-hook-form"; interface AdminListFiltersProps { @@ -14,6 +16,8 @@ interface AdminListFiltersProps { isMutating: number; handleFilterSubmit: UseFormHandleSubmit; search: (data: any) => void; + watch: UseFormWatch; + setValue: UseFormSetValue; } const AdminListFilters = ({ @@ -22,10 +26,12 @@ const AdminListFilters = ({ isMutating, handleFilterSubmit, search, + watch, + setValue, }: AdminListFiltersProps) => { return (
+ clearable + value={watch("role")} + onClear={() => setValue("role", undefined)} + /> */} {/* */} +