feat: add toast to user login change

This commit is contained in:
Kentai Radiquum 2025-03-21 23:55:03 +05:00
parent 83ad889408
commit 43d3aab01d
Signed by: Radiquum
GPG key ID: 858E8EE696525EED

View file

@ -1,11 +1,13 @@
"use client"; "use client";
import { Button, Modal, Textarea } from "flowbite-react"; import { Button, Modal, Textarea, useThemeMode } from "flowbite-react";
import { ENDPOINTS } from "#/api/config"; import { ENDPOINTS } from "#/api/config";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { useSWRConfig } from "swr"; import { useSWRConfig } from "swr";
import { Spinner } from "../Spinner/Spinner"; import { Spinner } from "../Spinner/Spinner";
import { unixToDate } from "#/api/utils"; import { unixToDate } from "#/api/utils";
import { toast } from "react-toastify";
import { tryCatchAPI } from "#/api/utils";
import { useUserStore } from "#/store/auth"; import { useUserStore } from "#/store/auth";
export const ProfileEditLoginModal = (props: { export const ProfileEditLoginModal = (props: {
@ -29,21 +31,33 @@ export const ProfileEditLoginModal = (props: {
const [_loginLength, _setLoginLength] = useState(0); const [_loginLength, _setLoginLength] = useState(0);
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const userStore = useUserStore(); const userStore = useUserStore();
const theme = useThemeMode();
useEffect(() => { useEffect(() => {
setLoading(true); async function _fetchLogin() {
fetch(`${ENDPOINTS.user.settings.login.info}?token=${props.token}`) setLoading(true);
.then((res) => {
if (res.ok) { const { data, error } = await tryCatchAPI(
return res.json(); fetch(`${ENDPOINTS.user.settings.login.info}?token=${props.token}`)
} );
})
.then((data) => { if (error) {
_setLoginData(data); toast.error("Ошибка получения текущего никнейма", {
_setLogin(data.login); autoClose: 2500,
_setLoginLength(data.login.length); isLoading: false,
closeOnClick: true,
draggable: true,
});
setLoading(false); setLoading(false);
}); props.setIsOpen(false);
return;
}
_setLoginData(data);
_setLogin(data.login);
_setLoginLength(data.login.length);
setLoading(false);
}
_fetchLogin();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.isOpen]); }, [props.isOpen]);
@ -52,43 +66,69 @@ export const ProfileEditLoginModal = (props: {
_setLoginLength(e.target.value.length); _setLoginLength(e.target.value.length);
} }
function _setLoginSetting() { async function _setLoginSetting() {
setSending(true);
if (!_login || _login == "") { if (!_login || _login == "") {
alert("Никнейм не может быть пустым"); toast.error("Никнейм не может быть пустым", {
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
});
return; return;
} }
fetch(
`${ENDPOINTS.user.settings.login.change}?login=${encodeURIComponent(
_login
)}&token=${props.token}`
)
.then((res) => {
if (res.ok) {
return res.json();
} else {
new Error("failed to send data");
}
})
.then((data) => {
if (data.code == 3) {
alert("Данный никнейм уже существует, попробуйте другой");
setSending(false);
return;
}
mutate( setSending(true);
`${ENDPOINTS.user.profile}/${props.profile_id}?token=${props.token}`
); const tid = toast.loading("Обновляем никнейм...", {
userStore.checkAuth(); position: "bottom-center",
props.setLogin(_login); hideProgressBar: true,
setSending(false); closeOnClick: false,
props.setIsOpen(false); pauseOnHover: false,
}) draggable: false,
.catch((err) => { theme: theme.mode == "light" ? "light" : "dark",
console.log(err); });
setSending(false);
const { data, error } = await tryCatchAPI(
fetch(
`${ENDPOINTS.user.settings.login.change}?login=${encodeURIComponent(
_login
)}&token=${props.token}`
)
);
if (error) {
let message = `Ошибка обновления никнейма: ${error.code}`;
if (error.code == 3) {
message = "Данный никнейм уже существует, попробуйте другой";
}
toast.update(tid, {
render: message,
type: "error",
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
}); });
setSending(false);
return;
}
toast.update(tid, {
render: "Никнейм обновлён",
type: "success",
autoClose: 2500,
isLoading: false,
closeOnClick: true,
draggable: true,
});
mutate(
`${ENDPOINTS.user.profile}/${props.profile_id}?token=${props.token}`
);
userStore.checkAuth();
props.setLogin(_login);
setSending(false);
props.setIsOpen(false);
} }
return ( return (
@ -100,13 +140,12 @@ export const ProfileEditLoginModal = (props: {
> >
<Modal.Header>Изменить никнейм</Modal.Header> <Modal.Header>Изменить никнейм</Modal.Header>
<Modal.Body> <Modal.Body>
{loading ? ( {loading ?
<div className="flex items-center justify-center py-8"> <div className="flex items-center justify-center py-8">
<Spinner /> <Spinner />
</div> </div>
) : ( : <>
<> {!_loginData.is_change_available ?
{!_loginData.is_change_available ? (
<> <>
<p>Вы недавно изменили никнейм</p> <p>Вы недавно изменили никнейм</p>
<p> <p>
@ -116,8 +155,7 @@ export const ProfileEditLoginModal = (props: {
</span> </span>
</p> </p>
</> </>
) : ( : <>
<>
<Textarea <Textarea
disabled={sending} disabled={sending}
rows={1} rows={1}
@ -132,9 +170,9 @@ export const ProfileEditLoginModal = (props: {
{_loginLength}/20 {_loginLength}/20
</p> </p>
</> </>
)} }
</> </>
)} }
</Modal.Body> </Modal.Body>
<Modal.Footer> <Modal.Footer>
{_loginData.is_change_available && ( {_loginData.is_change_available && (
@ -146,7 +184,11 @@ export const ProfileEditLoginModal = (props: {
Сохранить Сохранить
</Button> </Button>
)} )}
<Button color="red" onClick={() => props.setIsOpen(false)}> <Button
color="red"
onClick={() => props.setIsOpen(false)}
disabled={sending || loading}
>
Отмена Отмена
</Button> </Button>
</Modal.Footer> </Modal.Footer>