TTime/frontend/src/Components/ChangeUsername.tsx

62 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-03-19 03:39:05 +01:00
import React, { useState } from "react";
import InputField from "./InputField";
2024-03-21 02:22:23 +01:00
import { api } from "../API/API";
2024-03-19 03:39:05 +01:00
function ChangeUsername(): JSX.Element {
const [newUsername, setNewUsername] = useState("");
2024-03-21 02:22:23 +01:00
const [errorMessage, setErrorMessage] = useState("");
2024-03-19 03:39:05 +01:00
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
setNewUsername(e.target.value);
};
2024-03-21 02:22:23 +01:00
const handleSubmit = async (): Promise<void> => {
try {
// Call the API function to change the username
2024-03-21 02:51:28 +01:00
const token = localStorage.getItem("accessToken");
if (!token) {
throw new Error("Access token not found");
}
2024-03-21 02:22:23 +01:00
const response = await api.changeUserName(
{ prevName: "currentName", newName: newUsername },
2024-03-21 02:47:51 +01:00
token,
2024-03-21 02:22:23 +01:00
);
2024-03-21 02:51:28 +01:00
2024-03-21 02:22:23 +01:00
if (response.success) {
// Optionally, add a success message or redirect the user
console.log("Username changed successfully");
} else {
// Handle the error message
console.error("Failed to change username:", response.message);
2024-03-21 02:51:28 +01:00
setErrorMessage(response.message ?? "Failed to change username");
2024-03-21 02:22:23 +01:00
}
} catch (error) {
console.error("Error changing username:", error);
// Optionally, handle the error
setErrorMessage("Failed to change username");
}
};
const handleButtonClick = (): void => {
handleSubmit().catch((error) => {
console.error("Error in handleSubmit:", error);
});
};
2024-03-19 03:39:05 +01:00
return (
<div>
<InputField
label="New Username"
type="text"
value={newUsername}
onChange={handleChange}
/>
2024-03-21 02:22:23 +01:00
{errorMessage && <div>{errorMessage}</div>}
<button onClick={handleButtonClick}>Update Username</button>
2024-03-19 03:39:05 +01:00
</div>
);
}
export default ChangeUsername;