summaryrefslogtreecommitdiff
path: root/frontend/src/components/AddRobotForm.tsx
blob: 0d2a00f3d7d5ff8196f8488743bac37ff7697952 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import {
    useState,
    type ChangeEvent,
    type Dispatch,
    type SetStateAction,
} from "react";
import type { ErrorResponse } from "../types/error";
import type { CreateRobotResponse, Robot } from "../types/robot";

type Props = {
    apiUrl: string;
    errorMessage: string;
    robots: Robot[];
    token: string | null;
    setErrorMessage: Dispatch<SetStateAction<string>>;
    setIsAddingRobot: Dispatch<SetStateAction<boolean>>;
    setRobots: Dispatch<SetStateAction<Robot[]>>;
};

function AddRobotForm({
    apiUrl,
    errorMessage,
    robots,
    token,
    setErrorMessage,
    setIsAddingRobot,
    setRobots,
}: Props) {
    const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
    const [newRobotName, setNewRobotName] = useState<string>("");

    // Cancel robot creation
    function handleCancel() {
        setIsAddingRobot(false);
        setNewRobotName("");
        setErrorMessage("");
    }

    function handleInputChange(event: ChangeEvent<HTMLInputElement>) {
        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(data.message, data.robot);

            const newRobotList = [...robots, data.robot];
            setRobots(newRobotList);

            // 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 (
        <div className="add-robot-form">
            <input
                type="text"
                placeholder="Robot name..."
                value={newRobotName}
                onChange={handleInputChange}
                disabled={isSubmitting}
                autoFocus
            />
            <div className="add-robot-actions">
                <button
                    className="btn btn-start"
                    onClick={handleSubmit}
                    disabled={isSubmitting}
                >
                    {isSubmitting ? "Creating..." : "Create"}
                </button>
                <button
                    className="btn btn-stop"
                    onClick={handleCancel}
                    disabled={isSubmitting}
                >
                    Cancel
                </button>
            </div>
        </div>
    );
}

export default AddRobotForm;