|
| 1 | +import { Select } from "@sanity/ui"; |
| 2 | +import React, { useEffect, useState } from "react"; |
| 3 | +import { set, unset } from "sanity"; |
| 4 | +import type { StringInputProps } from "sanity"; |
| 5 | + |
| 6 | +type ComponentFolderOption = { |
| 7 | + title: string; |
| 8 | + value: string; |
| 9 | +}; |
| 10 | + |
| 11 | +export function ComponentFolderInput(props: StringInputProps) { |
| 12 | + const { value, onChange } = props; |
| 13 | + const [options, setOptions] = useState<ComponentFolderOption[]>([]); |
| 14 | + const [loading, setLoading] = useState<boolean>(true); |
| 15 | + |
| 16 | + const handleChange = React.useCallback( |
| 17 | + (event: React.FormEvent<HTMLSelectElement> | undefined) => { |
| 18 | + const value = event?.currentTarget.value; |
| 19 | + |
| 20 | + // If the selected option has a value, |
| 21 | + // it will be written to the document |
| 22 | + // otherwise the field will be cleared |
| 23 | + onChange(value ? set(value) : unset()); |
| 24 | + }, |
| 25 | + [onChange], |
| 26 | + ); |
| 27 | + |
| 28 | + useEffect(() => { |
| 29 | + async function fetchData() { |
| 30 | + try { |
| 31 | + const componentsResult = await fetch("/api/component-folders", { |
| 32 | + cache: "no-store", |
| 33 | + }); |
| 34 | + |
| 35 | + const components: ComponentFolderOption[] = |
| 36 | + await componentsResult.json(); |
| 37 | + |
| 38 | + const formattedOptions: ComponentFolderOption[] = |
| 39 | + components.map(({ title, value }) => ({ |
| 40 | + title, |
| 41 | + value, |
| 42 | + })); |
| 43 | + |
| 44 | + setOptions(formattedOptions); |
| 45 | + } catch (error) { |
| 46 | + console.error("Failed to fetch component folders:", error); |
| 47 | + } finally { |
| 48 | + setLoading(false); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + fetchData(); |
| 53 | + }, []); |
| 54 | + |
| 55 | + return ( |
| 56 | + <Select |
| 57 | + onChange={handleChange} |
| 58 | + disabled={loading || options.length === 0} |
| 59 | + value={value} |
| 60 | + > |
| 61 | + <option value="">-- Velg komponent --</option> |
| 62 | + {options.map((option) => ( |
| 63 | + <option key={option.value} value={option.value}> |
| 64 | + {option.title} |
| 65 | + </option> |
| 66 | + ))} |
| 67 | + </Select> |
| 68 | + ); |
| 69 | +} |
0 commit comments