import { useState, type ChangeEvent, type Dispatch, type SetStateAction, } from "react"; import type { ErrorResponse } from "../types/error"; import type { CreateRobotResponse } from "../types/robot"; type Props = { apiUrl: string; errorMessage: string; token: string | null; setErrorMessage: Dispatch>; setIsAddingRobot: Dispatch>; }; function AddRobotForm({ apiUrl, errorMessage, token, setErrorMessage, setIsAddingRobot, }: Props) { const [isSubmitting, setIsSubmitting] = useState(false); const [newRobotName, setNewRobotName] = useState(""); // Cancel robot creation function handleCancel() { setIsAddingRobot(false); setNewRobotName(""); setErrorMessage(""); } function handleInputChange(event: ChangeEvent) { if (errorMessage) { setErrorMessage(""); } setNewRobotName(event.target.value); } // Create new robot async function handleSubmit() { if (!newRobotName.trim()) { setErrorMessage("Please enter a name for the robot."); return; } setIsSubmitting(true); setErrorMessage(""); try { const response = await fetch(`${apiUrl}/robots`, { method: "POST", headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json", }, body: JSON.stringify({ name: newRobotName.trim() }), }); if (!response.ok) { const errorData: ErrorResponse = await response.json(); throw new Error( errorData.message || `Error creating the new robot: ${response.status}` ); } const data: CreateRobotResponse = await response.json(); console.log("Robot created successfully: ", data); // Reset form and close input field setNewRobotName(""); setIsAddingRobot(false); } catch (error) { console.error("Error creating the new robot:", error); if (error instanceof Error) { setErrorMessage(error.message); } else { setErrorMessage("Error creating the new robot."); } } finally { setIsSubmitting(false); } } return (
); } export default AddRobotForm;