import { Link } from 'react-router-dom' import { useState } from 'react' import { useForm } from 'react-hook-form' import { useMutation, useQueryClient } from '@tanstack/react-query' import toast from 'react-hot-toast' import type { AxiosError } from 'axios' import { devicesApi } from '../api' import DeviceCredentialsDialog from '../components/DeviceCredentialsDialog' import type { DeviceRegistrationRequest, DeviceRegistrationResponse } from '../types/api' type DeviceRegistrationForm = DeviceRegistrationRequest export default function AddDevice() { const queryClient = useQueryClient() const { register, handleSubmit, formState: { errors }, reset, } = useForm({ defaultValues: { protocol: 'mqtt', }, }) const [credentials, setCredentials] = useState(null) const [credentialsOpen, setCredentialsOpen] = useState(false) const registerMutation = useMutation({ mutationFn: (payload: DeviceRegistrationRequest) => devicesApi.create(payload), onSuccess: (response) => { setCredentials(response.data) setCredentialsOpen(true) toast.success('Device registered successfully') queryClient.invalidateQueries({ queryKey: ['devices'] }) reset({ name: '', location: '', protocol: 'mqtt' }) }, onError: (error) => { const axiosError = error as AxiosError<{ detail?: string }> const message = axiosError.response?.data?.detail || axiosError.message toast.error(`Failed to register device: ${message}`) }, }) const onSubmit = (data: DeviceRegistrationForm) => { if (data.protocol !== 'mqtt') { toast.error('Only MQTT devices are supported right now') return } registerMutation.mutate({ name: data.name.trim(), location: data.location?.trim() || undefined, protocol: 'mqtt', }) } return (
Back to Devices

Add New Device

Device Registration

Register a new IoT device. For MQTT devices, a certificate will be automatically generated.

{errors.name && ( )}
Cancel
{ setCredentialsOpen(open) if (!open) { setCredentials(null) } }} />
) }