Some fixes to ChangeUsername

This commit is contained in:
Peter KW 2024-04-01 02:14:44 +02:00
parent e06aced6dd
commit 9b0a231701

View file

@ -1,61 +1,26 @@
import React, { useState } from "react"; import { APIResponse, api } from "../API/API";
import InputField from "./InputField"; import { StrNameChange } from "../Types/goTypes";
import { api } from "../API/API";
function ChangeUsername(): JSX.Element {
const [newUsername, setNewUsername] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
setNewUsername(e.target.value);
};
const handleSubmit = async (): Promise<void> => {
try {
// Call the API function to change the username
const token = localStorage.getItem("accessToken");
if (!token) {
throw new Error("Access token not found");
}
const response = await api.changeUserName(
{ prevName: "currentName", newName: newUsername },
token,
);
function ChangeUsername(props: { nameChange: StrNameChange }): void {
if (props.nameChange.newName === "") {
alert("You have to select a new name");
return;
}
api
.changeUserName(props.nameChange, localStorage.getItem("accessToken") ?? "")
.then((response: APIResponse<void>) => {
if (response.success) { if (response.success) {
// Optionally, add a success message or redirect the user alert("Name changed successfully");
console.log("Username changed successfully"); location.reload();
} else { } else {
// Handle the error message alert("Name not changed");
console.error("Failed to change username:", response.message); console.error(response.message);
setErrorMessage(response.message ?? "Failed to change username");
} }
} catch (error) { })
console.error("Error changing username:", error); .catch((error) => {
// Optionally, handle the error alert("Name not changed");
setErrorMessage("Failed to change username"); console.error("An error occurred during change:", error);
}
};
const handleButtonClick = (): void => {
handleSubmit().catch((error) => {
console.error("Error in handleSubmit:", error);
}); });
};
return (
<div>
<InputField
label="New Username"
type="text"
value={newUsername}
onChange={handleChange}
/>
{errorMessage && <div>{errorMessage}</div>}
<button onClick={handleButtonClick}>Update Username</button>
</div>
);
} }
export default ChangeUsername; export default ChangeUsername;