chore: move api to another component
This commit is contained in:
@@ -6,29 +6,9 @@ import { ProfileImage } from './personalInformation/ProfileImage';
|
||||
import { InfoRowDisplay } from './personalInformation/InfoRowDisplay';
|
||||
import { InfoRowEdit } from './personalInformation/InfoRowEdit';
|
||||
import { PageWrapper } from '../PageWrapper';
|
||||
import { Gender, type InfoRowData } from '../../types';
|
||||
import axios, { isAxiosError } from 'axios';
|
||||
import apiClient from '@/lib/apiClient';
|
||||
|
||||
interface GetProfileApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
nationalCode?: string;
|
||||
gender?: Gender;
|
||||
countryCode?: string;
|
||||
profileImageUrl?: string;
|
||||
}
|
||||
|
||||
interface SaveProfileApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface TokenApiResponse {
|
||||
access_token: string;
|
||||
}
|
||||
import { useManualApi } from '@/hooks/useApi';
|
||||
import { Gender, type InfoRowData } from '../../types/settingsType';
|
||||
import { fetchProfile, saveProfile, getToken } from '../../api/settingsApi';
|
||||
|
||||
export function PersonalInformation() {
|
||||
const { t } = useTranslation('setting');
|
||||
@@ -42,71 +22,60 @@ export function PersonalInformation() {
|
||||
country: '',
|
||||
});
|
||||
const [originalData, setOriginalData] = useState<InfoRowData | null>(null);
|
||||
// const [token, setToken] = useState<string | null>(null);
|
||||
const [tokenError, setTokenError] = useState<string | null>(null);
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
const storedToken = localStorage.getItem('authToken');
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [fetchError, setFetchError] = useState<string | null>(null);
|
||||
const {
|
||||
data: profileData,
|
||||
loading: isLoadingProfile,
|
||||
error: fetchProfileError,
|
||||
execute: executeFetchProfile,
|
||||
} = useManualApi(fetchProfile);
|
||||
|
||||
const {
|
||||
data: saveData,
|
||||
loading: isSavingProfile,
|
||||
error: saveProfileError,
|
||||
execute: executeSaveProfile,
|
||||
} = useManualApi(saveProfile);
|
||||
|
||||
const {
|
||||
data: tokenData,
|
||||
loading: isGettingToken,
|
||||
error: tokenError,
|
||||
execute: executeGetToken,
|
||||
} = useManualApi(getToken);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchProfile = async () => {
|
||||
setIsLoading(true);
|
||||
setFetchError(null);
|
||||
try {
|
||||
const res = await apiClient.post<GetProfileApiResponse>(
|
||||
'/Profile/GetProfile',
|
||||
{},
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${storedToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (res.data?.success) {
|
||||
const profile = res.data;
|
||||
const fetchedData = {
|
||||
firstName: profile.firstName ?? '',
|
||||
lastName: profile.lastName ?? '',
|
||||
nationalCode: profile.nationalCode ?? '',
|
||||
gender: Object.values(Gender).includes(profile.gender as Gender)
|
||||
? (profile.gender as Gender)
|
||||
: Gender.None,
|
||||
country: profile.countryCode ?? '',
|
||||
};
|
||||
setData(fetchedData);
|
||||
setOriginalData(fetchedData);
|
||||
setUploadedImageUrl(profile.profileImageUrl || null);
|
||||
} else {
|
||||
throw new Error(res.data.message || t('settingForm.failRetrieve'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = t('settingForm.errorFetch');
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setFetchError(message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
executeFetchProfile();
|
||||
}, []);
|
||||
|
||||
if (storedToken) {
|
||||
fetchProfile();
|
||||
} else {
|
||||
setIsLoading(false);
|
||||
setFetchError(t('settingForm.notLoggedIn'));
|
||||
useEffect(() => {
|
||||
if (profileData?.success) {
|
||||
const fetchedData = {
|
||||
firstName: profileData.firstName ?? '',
|
||||
lastName: profileData.lastName ?? '',
|
||||
nationalCode: profileData.nationalCode ?? '',
|
||||
gender: Object.values(Gender).includes(profileData.gender as Gender)
|
||||
? (profileData.gender as Gender)
|
||||
: Gender.None,
|
||||
country: profileData.countryCode ?? '',
|
||||
};
|
||||
setData(fetchedData);
|
||||
setOriginalData(fetchedData);
|
||||
setUploadedImageUrl(profileData.profileImageUrl || null);
|
||||
}
|
||||
}, [storedToken, t]);
|
||||
}, [profileData]);
|
||||
|
||||
const initials = `${data?.firstName?.trim()[0] || ''}${
|
||||
data?.lastName?.trim()[0] || ''
|
||||
}`;
|
||||
useEffect(() => {
|
||||
if (saveData?.success) {
|
||||
setIsEditing(false);
|
||||
setOriginalData(data);
|
||||
}
|
||||
}, [saveData, data]);
|
||||
|
||||
const initials = `${data?.firstName?.trim()[0] || ''}${data?.lastName?.trim()[0] || ''}`;
|
||||
|
||||
const handleEditClick = () => {
|
||||
setIsEditing(true);
|
||||
setSaveError(null);
|
||||
setOriginalData(data);
|
||||
};
|
||||
|
||||
@@ -115,85 +84,21 @@ export function PersonalInformation() {
|
||||
if (originalData) {
|
||||
setData(originalData);
|
||||
}
|
||||
setSaveError(null);
|
||||
};
|
||||
|
||||
const handleSaveClick = async () => {
|
||||
if (!data) return;
|
||||
setSaveError(null);
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('FirstName', data.firstName || '');
|
||||
formData.append('LastName', data.lastName || '');
|
||||
formData.append('NationalCode', data.nationalCode || '');
|
||||
formData.append('Gender', String(data.gender ?? Gender.None));
|
||||
formData.append('CountryCode', data.country || '');
|
||||
|
||||
if (uploadedImageUrl && uploadedImageUrl.startsWith('data:')) {
|
||||
const response = await fetch(uploadedImageUrl);
|
||||
const blob = await response.blob();
|
||||
formData.append('Image', blob, 'profile.jpg');
|
||||
}
|
||||
|
||||
const res = await apiClient.post<SaveProfileApiResponse>(
|
||||
'Profile/SaveProfilePersonalInforamtion',
|
||||
formData,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${storedToken}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
if (res.data.success) {
|
||||
setIsEditing(false);
|
||||
setOriginalData(data);
|
||||
} else {
|
||||
throw new Error(res.data.message || t('settingForm.unknownError'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = t('settingForm.checkConnection');
|
||||
if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setSaveError(message);
|
||||
}
|
||||
executeSaveProfile({ data, imageUrl: uploadedImageUrl });
|
||||
};
|
||||
|
||||
const apiUrl = 'https://accounts.business-harmony.com';
|
||||
const tokenEndpoint = `${apiUrl}/connect/token`;
|
||||
const getToken = async () => {
|
||||
setTokenError(null);
|
||||
try {
|
||||
const body = new URLSearchParams();
|
||||
body.set('grant_type', 'password');
|
||||
body.set('username', 'zareian.1381@gmail.com');
|
||||
body.set('password', '123@Qweasd');
|
||||
body.set('client_id', 'harmony_identity');
|
||||
body.set('scope', 'openid harmony_identity profile offline_access');
|
||||
const response = await axios.post<TokenApiResponse>(
|
||||
tokenEndpoint,
|
||||
body.toString(),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
},
|
||||
);
|
||||
if (response.data?.access_token) {
|
||||
localStorage.setItem('authToken', response.data.access_token);
|
||||
} else {
|
||||
throw new Error('No access token in response');
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
let message = 'Failed to get token';
|
||||
if (isAxiosError(error) && error.response) {
|
||||
message = `Request failed with status ${error.response.status}`;
|
||||
} else if (error instanceof Error) {
|
||||
message = error.message;
|
||||
}
|
||||
setTokenError(message);
|
||||
}
|
||||
const handleGetTokenClick = async () => {
|
||||
executeGetToken();
|
||||
};
|
||||
|
||||
const getErrorMessage = (error: unknown): string | null => {
|
||||
if (!error) return null;
|
||||
if (error instanceof Error) return error.message;
|
||||
return String(error);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -222,12 +127,12 @@ export function PersonalInformation() {
|
||||
<Button
|
||||
variant="contained"
|
||||
color="secondary"
|
||||
onClick={getToken}
|
||||
onClick={handleGetTokenClick}
|
||||
size="large"
|
||||
sx={{ textTransform: 'none' }}
|
||||
disabled={isLoading}
|
||||
disabled={isLoadingProfile || isGettingToken || isSavingProfile}
|
||||
>
|
||||
Get Token
|
||||
{isGettingToken ? <CircularProgress size={24} /> : 'Get Token'}
|
||||
</Button>
|
||||
{isEditing ? (
|
||||
<>
|
||||
@@ -240,6 +145,7 @@ export function PersonalInformation() {
|
||||
textTransform: 'none',
|
||||
width: { xs: '100%', sm: 'auto' },
|
||||
}}
|
||||
disabled={isSavingProfile}
|
||||
>
|
||||
{t('settingForm.rejectButton')}
|
||||
</Button>
|
||||
@@ -251,8 +157,13 @@ export function PersonalInformation() {
|
||||
textTransform: 'none',
|
||||
width: { xs: '100%', sm: 'auto' },
|
||||
}}
|
||||
disabled={isSavingProfile}
|
||||
>
|
||||
{t('settingForm.saveButton')}
|
||||
{isSavingProfile ? (
|
||||
<CircularProgress size={24} color="inherit" />
|
||||
) : (
|
||||
t('settingForm.saveButton')
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
@@ -260,27 +171,33 @@ export function PersonalInformation() {
|
||||
onClick={handleEditClick}
|
||||
size="large"
|
||||
variant="outlined"
|
||||
sx={{
|
||||
borderRadius: 1,
|
||||
}}
|
||||
disabled={isLoading}
|
||||
sx={{ borderRadius: 1 }}
|
||||
disabled={isLoadingProfile}
|
||||
>
|
||||
{t('settingForm.editButton')}
|
||||
</Button>
|
||||
)}
|
||||
</Box>
|
||||
{saveError && (
|
||||
{getErrorMessage(saveProfileError) && (
|
||||
<Typography
|
||||
color="error"
|
||||
sx={{ mt: 1, textAlign: 'right', width: '100%' }}
|
||||
>
|
||||
{saveError}
|
||||
{getErrorMessage(saveProfileError)}
|
||||
</Typography>
|
||||
)}
|
||||
{tokenData?.success && (
|
||||
<Typography
|
||||
color="green"
|
||||
sx={{ mt: 1, textAlign: 'right', width: '100%' }}
|
||||
>
|
||||
Token fetched and stored successfully!
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
}
|
||||
>
|
||||
{isLoading ? (
|
||||
{isLoadingProfile ? (
|
||||
<Box
|
||||
sx={{
|
||||
display: 'flex',
|
||||
@@ -292,14 +209,19 @@ export function PersonalInformation() {
|
||||
>
|
||||
<CircularProgress />
|
||||
</Box>
|
||||
) : fetchError ? (
|
||||
) : fetchProfileError ? (
|
||||
<Box sx={{ textAlign: 'center', p: 4 }}>
|
||||
<Typography color="error">{fetchError}</Typography>
|
||||
<Typography color="error">
|
||||
{getErrorMessage(fetchProfileError) ||
|
||||
t('settingForm.errorFetch')}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<>
|
||||
{tokenError && (
|
||||
<Box sx={{ mt: 2, color: 'red' }}>Error: {tokenError}</Box>
|
||||
{getErrorMessage(tokenError) && (
|
||||
<Box sx={{ p: 2, mx: { xs: 2, sm: 3, md: 4 }, color: 'red' }}>
|
||||
Error: {getErrorMessage(tokenError)}
|
||||
</Box>
|
||||
)}
|
||||
<Box
|
||||
sx={{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import { useState, useRef, useEffect, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import parsePhoneNumberFromString from 'libphonenumber-js';
|
||||
import { PageWrapper } from '../PageWrapper';
|
||||
@@ -6,9 +6,15 @@ import { CardContainer } from '@/components/CardContainer';
|
||||
import PhoneDisplay from './phoneNumber/PhoneDisplay';
|
||||
import PhoneEditForm from './phoneNumber/PhoneEditForm';
|
||||
import PhoneActionButtons from './phoneNumber/PhoneActionButtons';
|
||||
import apiClient from '@/lib/apiClient';
|
||||
import { CircularProgress, Box, Typography } from '@mui/material';
|
||||
import { toLocaleDigits } from '@/utils/persianDigit';
|
||||
import { useManualApi } from '@/hooks/useApi';
|
||||
import {
|
||||
fetchProfile,
|
||||
sendVerificationCode,
|
||||
confirmPhoneNumberCode,
|
||||
changePhoneNumber,
|
||||
} from '../../api/settingsApi';
|
||||
|
||||
interface Phone {
|
||||
phone: string;
|
||||
@@ -16,21 +22,6 @@ interface Phone {
|
||||
withCode: string;
|
||||
}
|
||||
|
||||
interface GetProfileApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
phoneNumber?: string;
|
||||
}
|
||||
|
||||
interface ApiResponse {
|
||||
success: boolean;
|
||||
message?: string;
|
||||
}
|
||||
|
||||
interface ConfirmApiResponse extends ApiResponse {
|
||||
confirm?: boolean;
|
||||
}
|
||||
|
||||
export function PhoneNumber() {
|
||||
const { t, i18n } = useTranslation('setting');
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
@@ -40,185 +31,158 @@ export function PhoneNumber() {
|
||||
const [buttonState, setButtonState] = useState<'default' | 'counting'>(
|
||||
'default',
|
||||
);
|
||||
const [isVerifying, setIsVerifying] = useState(false);
|
||||
const [isVerified, setIsVerified] = useState(false);
|
||||
const [phones, setPhone] = useState<Phone[]>([]);
|
||||
const [phones, setPhones] = useState<Phone[]>([]);
|
||||
const [countryCode, setCountryCode] = useState('+98');
|
||||
const [formError, setFormError] = useState<string>();
|
||||
const [touched, setTouched] = useState<boolean>(false);
|
||||
|
||||
const textFieldRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
const [error, setError] = useState<string>();
|
||||
const [touched, setTouched] = useState<boolean>(false);
|
||||
const inputError: boolean = touched && !!error;
|
||||
const token = localStorage.getItem('authToken');
|
||||
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [fetchError, setFetchError] = useState<string | null>(null);
|
||||
const {
|
||||
data: profileData,
|
||||
loading: isLoading,
|
||||
error: fetchError,
|
||||
execute: executeFetchProfile,
|
||||
} = useManualApi(fetchProfile);
|
||||
|
||||
const {
|
||||
data: sendCodeData,
|
||||
loading: isSendingCode,
|
||||
error: sendCodeError,
|
||||
execute: executeSendCode,
|
||||
} = useManualApi(sendVerificationCode);
|
||||
|
||||
const {
|
||||
data: confirmData,
|
||||
loading: isVerifying,
|
||||
error: confirmError,
|
||||
execute: executeConfirmCode,
|
||||
} = useManualApi(confirmPhoneNumberCode);
|
||||
|
||||
const {
|
||||
data: changePhoneData,
|
||||
loading: isChangingPhone,
|
||||
error: changePhoneError,
|
||||
execute: executeChangePhone,
|
||||
} = useManualApi(changePhoneNumber);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchPhoneNumber = async () => {
|
||||
setIsLoading(true);
|
||||
setFetchError(null);
|
||||
if (!token) {
|
||||
setIsLoading(false);
|
||||
setFetchError(t('settingForm.notLoggedIn'));
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await apiClient.post<GetProfileApiResponse>(
|
||||
'/Profile/GetProfile',
|
||||
{},
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
if (!isEditing) {
|
||||
executeFetchProfile();
|
||||
}
|
||||
}, [isEditing]);
|
||||
|
||||
if (res.data.success && res.data.phoneNumber) {
|
||||
setPhone([
|
||||
{
|
||||
phone: res.data.phoneNumber,
|
||||
time: '',
|
||||
withCode: res.data.phoneNumber,
|
||||
},
|
||||
]);
|
||||
} else if (!res.data.success) {
|
||||
throw new Error(
|
||||
res.data.message || t('settingForm.failFetchPhoneNumber'),
|
||||
);
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
let message = t('settingForm.errorFetchPhoneNumber');
|
||||
if (err instanceof Error) {
|
||||
message = err.message;
|
||||
}
|
||||
setFetchError(message);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
useEffect(() => {
|
||||
if (profileData?.success && profileData.phoneNumber) {
|
||||
setPhones([
|
||||
{
|
||||
phone: profileData.phoneNumber,
|
||||
time: '',
|
||||
withCode: profileData.phoneNumber,
|
||||
},
|
||||
]);
|
||||
}
|
||||
}, [profileData]);
|
||||
|
||||
fetchPhoneNumber();
|
||||
}, [token, t]);
|
||||
useEffect(() => {
|
||||
if (sendCodeData?.success) {
|
||||
setButtonState('counting');
|
||||
setIsVerified(false);
|
||||
}
|
||||
}, [sendCodeData]);
|
||||
|
||||
useEffect(() => {
|
||||
if (confirmData?.success && confirmData.confirm) {
|
||||
setIsVerified(true);
|
||||
setShowToast(true);
|
||||
const fullPhoneNumber = countryCode + phoneNumber.replace(/^0/, '');
|
||||
executeChangePhone({ phoneNumber: fullPhoneNumber });
|
||||
}
|
||||
}, [confirmData, countryCode, phoneNumber, executeChangePhone]);
|
||||
|
||||
useEffect(() => {
|
||||
if (changePhoneData?.success) {
|
||||
const fullPhoneNumber = countryCode + phoneNumber.replace(/^0/, '');
|
||||
setPhones([
|
||||
{
|
||||
phone: phoneNumber,
|
||||
time: t('settingForm.justNow'),
|
||||
withCode: fullPhoneNumber,
|
||||
},
|
||||
]);
|
||||
setIsEditing(false);
|
||||
}
|
||||
}, [changePhoneData, countryCode, phoneNumber, t]);
|
||||
|
||||
const apiError = useMemo(
|
||||
() => sendCodeError || confirmError || changePhoneError,
|
||||
[sendCodeError, confirmError, changePhoneError],
|
||||
);
|
||||
|
||||
const getErrorMessage = (error: unknown): string | undefined => {
|
||||
if (!error) return undefined;
|
||||
if (error instanceof Error) return error.message;
|
||||
return String(error);
|
||||
};
|
||||
|
||||
const isPhoneValid = (code: string, phone: string) => {
|
||||
const phoneNum = parsePhoneNumberFromString(code + phone);
|
||||
return phoneNum && phoneNum.isValid();
|
||||
return phoneNum?.isValid();
|
||||
};
|
||||
|
||||
const handleBlur = () => {
|
||||
setTouched(true);
|
||||
if (!phoneNumber) {
|
||||
setError(t('settingForm.thisFieldIsRequired'));
|
||||
setFormError(t('settingForm.thisFieldIsRequired'));
|
||||
return;
|
||||
}
|
||||
if (!isPhoneValid(countryCode, phoneNumber)) {
|
||||
setError(t('settingForm.phoneNumberIsInvalid'));
|
||||
setFormError(t('settingForm.phoneNumberIsInvalid'));
|
||||
} else {
|
||||
setError(undefined);
|
||||
setFormError(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleEdit = () => {
|
||||
setIsEditing((prev) => {
|
||||
const enteringEditMode = !prev;
|
||||
if (enteringEditMode) {
|
||||
if (!prev) {
|
||||
setPhoneNumber('');
|
||||
setVerificationCode('');
|
||||
setIsVerified(false);
|
||||
setButtonState('default');
|
||||
setShowToast(false);
|
||||
setError(undefined);
|
||||
setFormError(undefined);
|
||||
setTouched(false);
|
||||
}
|
||||
return enteringEditMode;
|
||||
return !prev;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSendCode = async () => {
|
||||
if (!phoneNumber) return;
|
||||
if (!isPhoneValid(countryCode, phoneNumber)) {
|
||||
setError(t('settingForm.phoneNumberIsInvalid'));
|
||||
return;
|
||||
}
|
||||
setError(undefined);
|
||||
const handleSendCode = () => {
|
||||
handleBlur();
|
||||
if (formError || !isPhoneValid(countryCode, phoneNumber)) return;
|
||||
|
||||
try {
|
||||
const res = await apiClient.post<ApiResponse>(
|
||||
'/Profile/SendVerfiyPhoneNumberCode',
|
||||
{
|
||||
phoneNumber: countryCode + phoneNumber.replace(/^0/, ''),
|
||||
},
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
if (res.data.success) {
|
||||
setButtonState('counting');
|
||||
setIsVerified(false);
|
||||
} else {
|
||||
setError(res.data.message || t('settingForm.sendCodeFailed'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
setError(t('settingForm.sendCodeFailed'));
|
||||
}
|
||||
executeSendCode({
|
||||
phoneNumber: countryCode + phoneNumber.replace(/^0/, ''),
|
||||
});
|
||||
};
|
||||
|
||||
const handleVerifyCode = async () => {
|
||||
const handleVerifyCode = () => {
|
||||
if (!verificationCode) {
|
||||
setError(t('settingForm.verificationCodeRequired'));
|
||||
setFormError(t('settingForm.verificationCodeRequired'));
|
||||
return;
|
||||
}
|
||||
setIsVerifying(true);
|
||||
setError(undefined);
|
||||
|
||||
try {
|
||||
const res = await apiClient.post<ConfirmApiResponse>(
|
||||
'/Profile/ConfirmPhoneNumberChangeCode',
|
||||
{
|
||||
phoneNumber: countryCode + phoneNumber.replace(/^0/, ''),
|
||||
verifyCode: verificationCode,
|
||||
},
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
|
||||
if (res.data.success && res.data.confirm) {
|
||||
setIsVerified(true);
|
||||
setShowToast(true);
|
||||
await handleChangePhoneNumber();
|
||||
} else {
|
||||
setError(res.data.message || t('settingForm.verifyCodeFailed'));
|
||||
setIsVerified(false);
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
setError(t('settingForm.verifyCodeFailed'));
|
||||
setIsVerified(false);
|
||||
} finally {
|
||||
setIsVerifying(false);
|
||||
}
|
||||
setFormError(undefined);
|
||||
executeConfirmCode({
|
||||
phoneNumber: countryCode + phoneNumber.replace(/^0/, ''),
|
||||
verifyCode: verificationCode,
|
||||
});
|
||||
};
|
||||
|
||||
const handleChangePhoneNumber = async () => {
|
||||
try {
|
||||
const fullPhoneNumber = countryCode + phoneNumber.replace(/^0/, '');
|
||||
const res = await apiClient.post<ApiResponse>(
|
||||
'/Profile/ChangePhoneNumber',
|
||||
{
|
||||
phoneNumber: fullPhoneNumber,
|
||||
},
|
||||
{ headers: { Authorization: `Bearer ${token}` } },
|
||||
);
|
||||
|
||||
if (res.data.success) {
|
||||
setPhone([
|
||||
{
|
||||
phone: phoneNumber,
|
||||
time: t('settingForm.justNow'),
|
||||
withCode: fullPhoneNumber,
|
||||
},
|
||||
]);
|
||||
setIsEditing(false);
|
||||
} else {
|
||||
setError(res.data.message || t('settingForm.changePhoneFailed'));
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
setError(t('settingForm.changePhoneFailed'));
|
||||
}
|
||||
};
|
||||
const combinedError = formError || getErrorMessage(apiError);
|
||||
const inputError: boolean = touched && !!combinedError;
|
||||
|
||||
return (
|
||||
<PageWrapper>
|
||||
@@ -248,7 +212,10 @@ export function PhoneNumber() {
|
||||
</Box>
|
||||
) : fetchError ? (
|
||||
<Box sx={{ textAlign: 'center', p: 4 }}>
|
||||
<Typography color="error">{fetchError}</Typography>
|
||||
<Typography color="error">
|
||||
{getErrorMessage(fetchError) ||
|
||||
t('settingForm.errorFetchPhoneNumber')}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : isEditing ? (
|
||||
<PhoneEditForm
|
||||
@@ -259,12 +226,12 @@ export function PhoneNumber() {
|
||||
verificationCode={verificationCode}
|
||||
setVerificationCode={setVerificationCode}
|
||||
isVerified={isVerified}
|
||||
isVerifying={isVerifying}
|
||||
isVerifying={isVerifying || isSendingCode || isChangingPhone}
|
||||
buttonState={buttonState}
|
||||
setButtonState={setButtonState}
|
||||
handleSendCode={handleSendCode}
|
||||
handleVerifyClick={handleVerifyCode}
|
||||
error={error}
|
||||
error={combinedError}
|
||||
inputError={inputError}
|
||||
handleBlur={handleBlur}
|
||||
textFieldRef={textFieldRef as React.RefObject<HTMLDivElement>}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Box, Typography, Avatar } from '@mui/material';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { DisplayField } from './DisplayField';
|
||||
import { CountryFlag } from '@/components/CountryFlag';
|
||||
import { Gender } from '@/features/profile/types';
|
||||
import { Gender } from '@/features/profile/types/settingsType';
|
||||
|
||||
interface InfoRowData {
|
||||
firstName: string;
|
||||
|
||||
@@ -10,8 +10,8 @@ import {
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { countries } from '@/features/profile/data/countries';
|
||||
import { CountryFlag } from '@/components/CountryFlag';
|
||||
import { Gender } from '@/features/profile/types';
|
||||
import { type InfoRowData } from '@/features/profile/types';
|
||||
import { Gender } from '@/features/profile/types/settingsType';
|
||||
import { type InfoRowData } from '@/features/profile/types/settingsType';
|
||||
|
||||
interface InfoRowEditProps {
|
||||
data: InfoRowData;
|
||||
|
||||
Reference in New Issue
Block a user