export default function DeviceTypeCreate()

in source/console/src/views/DeviceTypeCreate.tsx [26:151]


export default function DeviceTypeCreate(props: IProps): JSX.Element {
    const history = useHistory();
    const logger = new Logger("Device Type Create");
    let location = useLocation<{ originalDeviceType?: IDeviceType }>();
    let originalDeviceType = null;

    if (location.state) {
        originalDeviceType = location.state.originalDeviceType;
    }

    const [deviceType, setDeviceType] = useState<IDeviceType>(
        originalDeviceType ?
            originalDeviceType :
            {
                name: "",
                topic: "",
                typeId: "",
                payload: []
            }
    );
    const [showAttrFormModal, setShowAttrFormModal] = useState<boolean>(false);
    const [showAttrModal, setShowAttrModal] = useState<string>("");
    const [refAttrPayload, setRefAttrPayload] = useState<IAttribute[] | undefined>(undefined);
    const [errs, setErrs] = useState<IErrors<IDeviceType>>({});
    const [showAlert, setShowAlert] = useState("");
    const [showValidation, setShowValidation] = useState<string[]>([]);

    /**
     * react useEffect hoook
     * runs on device type state change
     * validates device type form fields
     */
    useEffect(() => {
        let newErrs = {};
        Object.entries(deviceType).forEach((entry) => {
            const key = entry[0];
            const value = entry[1];
            if (key === "name" || key === "topic") {
                let error: any = validateField(key, value);
                newErrs = { ...newErrs, ...error }
            }
        })
        setErrs({ ...newErrs });
    }, [deviceType])

    /**
     * updates state on form changes
     * @param event 
     */
    const handleFormChange = (event: any) => {
        deviceType[event.target.id as keyof IDeviceType] = event.target.value;
        setDeviceType({ ...deviceType })
    }

    /**
     * Shows form validation when a field is focused
     * @param event 
     */
    const handleFieldFocus = (event: any) => {
        if(!showValidation.includes(event.target.id)) {
            showValidation.push(event.target.id);
            setShowValidation([...showValidation]);
        }
    }

    /**
     * updates payload attributes based on device type
     * @param newAttr 
     */
    const handleModalSubmit = (newAttr: IAttribute) => {
        if (refAttrPayload) {
            refAttrPayload.push(newAttr);
        } else {
            deviceType.payload.push(newAttr);
        }
        setDeviceType({ ...deviceType });
    }

    /**
     * updates dynamodb on form submission
     */
    const handleSubmit = async (event: any) => {
        const form = event.currentTarget;
        event.preventDefault();
        form.checkValidity();
        if (Object.keys(errs).length > 0) {
            return;
        }

        try {
            await API.post(API_NAME, '/devicetypes', { body: deviceType });
            history.push('/device-types');
        } catch (err) {
            logger.error(I18n.get("device.type.create.error"), err);
            throw err;
        }

    }

    /**
     * resets state on modal close
     */
    const closeAttrFormModal = () => {
        setRefAttrPayload(undefined);
        setShowAttrFormModal(false);
    }

    /**
     * 
     * @param attr 
     * @returns Modal which displays attribute
     */
    const attributeModal = (attr: IAttribute, indicesString: string) => {
        return (
            <Modal show={showAttrModal === indicesString} onHide={() => setShowAttrModal("")}>
                <Modal.Header closeButton>
                    <Modal.Title>
                        {attr.name}
                    </Modal.Title>
                </Modal.Header>
                <Modal.Body>
                    <pre>{JSON.stringify(attr, null, 2)}</pre>
                </Modal.Body>
            </Modal>
        )
    }