import { useField } from 'formik'; import type { ChangeEvent } from 'react'; import { useEffect, useState } from 'react'; import type { WithRelationships } from '@/api/admin'; import type { Egg } from '@/api/admin/egg'; import { searchEggs } from '@/api/admin/egg'; import Label from '@/components/elements/Label'; import Select from '@/components/elements/Select'; interface Props { nestId?: number; selectedEggId?: number; onEggSelect: (egg: Egg | null) => void; } export default ({ nestId, selectedEggId, onEggSelect }: Props) => { const [, , { setValue, setTouched }] = useField>('environment'); const [eggs, setEggs] = useState[] | null>(null); const selectEgg = (egg: Egg | null) => { if (egg === null) { onEggSelect(null); return; } // Clear values setValue({}); setTouched(true); onEggSelect(egg); const values: Record = {}; egg.relationships.variables?.forEach(v => { values[v.environmentVariable] = v.defaultValue; }); setValue(values); setTouched(true); }; useEffect(() => { if (!nestId) { setEggs(null); return; } searchEggs(nestId, {}) .then(eggs => { setEggs(eggs); selectEgg(eggs[0] || null); }) .catch(error => console.error(error)); }, [nestId]); const onSelectChange = (e: ChangeEvent) => { selectEgg(eggs?.find(egg => egg.id.toString() === e.currentTarget.value) || null); }; return ( <> ); };