import React, { useRef } from 'react'; import { ErrorMessage } from '@hookform/error-message'; import { TOPIC_CUSTOM_PARAMS } from 'lib/constants'; import { FieldArrayWithId, useFormContext, Controller } from 'react-hook-form'; import { TopicFormData } from 'redux/interfaces'; import { InputLabel } from 'components/common/Input/InputLabel.styled'; import { FormError } from 'components/common/Input/Input.styled'; import Select from 'components/common/Select/Select'; import Input from 'components/common/Input/Input'; import IconButtonWrapper from 'components/common/Icons/IconButtonWrapper'; import CloseIcon from 'components/common/Icons/CloseIcon'; import * as C from 'components/Topics/shared/Form/TopicForm.styled'; import * as S from './CustomParams.styled'; export interface Props { isDisabled: boolean; index: number; existingFields: string[]; field: FieldArrayWithId; remove: (index: number) => void; setExistingFields: React.Dispatch>; } const CustomParamField: React.FC = ({ field, isDisabled, index, remove, existingFields, setExistingFields, }) => { const { formState: { errors }, setValue, watch, control, } = useFormContext(); const nameValue = watch(`customParams.${index}.name`); const prevName = useRef(nameValue); React.useEffect(() => { if (nameValue !== prevName.current) { let newExistingFields = [...existingFields]; if (prevName.current) { newExistingFields = newExistingFields.filter( (name) => name !== prevName.current ); } prevName.current = nameValue; newExistingFields.push(nameValue); setExistingFields(newExistingFields); setValue(`customParams.${index}.value`, TOPIC_CUSTOM_PARAMS[nameValue], { shouldValidate: true, }); } }, [existingFields, index, nameValue, setExistingFields, setValue]); return (
Custom Parameter (
remove(index)} onKeyDown={(e: React.KeyboardEvent) => e.code === 'Space' && remove(index) } title={`Delete customParam field ${index}`} >
); }; export default React.memo(CustomParamField);