TTime/frontend/src/Components/ChangeUsername.tsx

55 lines
1.5 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
const response = await api.changeUserName(
{ prevName: "currentName", newName: newUsername },
"token",
);
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);
}
} 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;