implementing changeUsername component

This commit is contained in:
pavel Hamawand 2024-03-21 02:22:23 +01:00
parent 3e11b87eee
commit 1950112202

View file

@ -1,23 +1,41 @@
import React, { useState } from "react";
import InputField from "./InputField";
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 update the username
// await api.updateUsername(newUsername);
// // Optionally, add a success message or redirect the user
// } catch (error) {
// console.error("Error updating username:", error);
// // Optionally, handle the error
// }
// };
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);
});
};
return (
<div>
@ -27,6 +45,8 @@ function ChangeUsername(): JSX.Element {
value={newUsername}
onChange={handleChange}
/>
{errorMessage && <div>{errorMessage}</div>}
<button onClick={handleButtonClick}>Update Username</button>
</div>
);
}