server/assets/js/react/components/SelectLanguage.tsx

45 lines
1.2 KiB
TypeScript
Raw Normal View History

import * as React from "react"
import { SelectProps } from "@mui/base/Select"
2023-12-05 22:55:01 +00:00
import type { Language } from "../types/Language"
import { Select, Option } from "./Select"
2023-12-06 02:46:27 +00:00
import { useLanguagesQuery } from "../utils/queries"
export type SelectLanguageProps = SelectProps<{}, boolean>
export const SelectLanguage = React.forwardRef(function SelectLanguage(
props: SelectLanguageProps,
ref: React.ForwardedRef<HTMLButtonElement>
) {
const id = React.useId()
2023-12-05 22:55:01 +00:00
const [options, setOptions] = React.useState<Language[] | null>(null)
const { defaultValue, ...other } = props
2023-12-06 02:46:27 +00:00
const { isLoading, data } = useLanguagesQuery()
React.useEffect(() => {
2023-12-05 22:55:01 +00:00
if (data) {
setOptions(data)
}
}, [data])
return (
<Select
ref={ref}
2023-12-05 22:55:01 +00:00
// Use key to force re-render and ensure the defaultValue takes effect.
key={!options && isLoading ? `${id}-loading` : `${id}-loaded`}
className={!options && isLoading ? "text-slate-900/60" : ""}
defaultValue={!options && isLoading ? [""] : defaultValue}
{...other}
>
2023-12-05 22:55:01 +00:00
{options?.map((lang, index) => {
return (
2023-12-05 22:55:01 +00:00
<Option key={index} value={lang.code}>
{lang.name}
</Option>
)
})}
</Select>
)
})