import { FC, useEffect, useState } from 'react' import Input from '../../../components/Input' import { Edit } from 'iconsax-react' import { useTranslation } from 'react-i18next' import Button from '../../../components/Button' import { useCheckUserName, useUpdateProfile } from '../hooks/useProfileData' import { CheckUserNameType, UpdateProfileType } from '../types/ProfileTypes' import { toast } from '../../../components/Toast' import { ErrorType } from '../../../helpers/types' type Props = { username: string | null, } const Username: FC = (props: Props) => { const { t } = useTranslation('global') const [username, setUsername] = useState(props.username ? props.username : '') const [canSave, setCanSave] = useState(false) const [canEdit, setCanEdit] = useState(false) const [status, setStatus] = useState<'success' | 'error' | ''>('') const checkUsername = useCheckUserName() const updateProfile = useUpdateProfile() const handleChange = (e: React.ChangeEvent) => { const value = e.target.value setCanSave(false) if (value.indexOf(' ') === -1) { if (value.length <= 3) { setUsername(value) return } setStatus('') const params: CheckUserNameType = { value: e.target.value, type: 'userName' } setUsername(e.target.value) checkUsername.mutate(params, { onSuccess() { setStatus('success') setCanSave(true) }, onError() { setStatus('error') } }) } } const handleSave = () => { const params: UpdateProfileType = { userName: username } updateProfile.mutate(params, { onSuccess: () => { toast(t('profile.username_save_success'), 'success') setCanEdit(false) setCanSave(false) setStatus('') }, onError(error: ErrorType) { toast(error.response?.data?.error?.message[0], 'error') }, }) } useEffect(() => { if (username !== props.username) { setUsername(props.username ? props.username : '') } }, [props.username]) return ( <>
{ checkUsername.isPending &&
}
{ !canEdit ?
setCanEdit(true)} className='flex gap-1 cursor-pointer relative -top-3'>
{t('edit')}
:
{ status === 'success' ?
{t('profile.username_available')}
: status === 'error' ?
{t('profile.username_not_available')}
: null } ) } export default Username