sozsoft-platform/ui/src/utils/hooks/useAccount.ts

81 lines
2 KiB
TypeScript

import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ROUTES_ENUM } from '@/routes/route.constant'
import {
sendAccountConfirmationCode,
verifyAccountConfirmationCode,
} from '../../services/account.service'
function useAccount() {
const [message, setMessage] = useState('')
const [error, setError] = useState('')
const navigate = useNavigate()
const sendConfirmationCode = async (values: any) => {
try {
const result = await sendAccountConfirmationCode(values)
if (result.data !== true) {
throw new Error('This email is already confirmed or no account was found.')
}
setError('')
setMessage('Verification code has been sent to your e-mail address.')
return {
status: 'success',
}
} catch (error: any) {
const err =
error?.response?.data?.error?.message ||
error?.response?.data?.message ||
error?.message ||
error.toString()
setMessage('')
setError(err)
return {
status: 'failed',
message: err,
}
}
}
const verifyConfirmationCode = async (userId: string, token: string) => {
if (!userId || !token) {
return {
status: 'failed',
message: 'Invalid user and token',
}
}
try {
const result = await verifyAccountConfirmationCode(userId, token)
if (result.data) {
setError('')
setMessage('Your account is confirmed')
setTimeout(() => {
navigate(ROUTES_ENUM.authenticated.login)
}, 3000)
} else {
throw new Error('Invalid token')
}
return result
} catch (error: any) {
const err =
error?.response?.data?.error?.message || error?.response?.data?.message || error.toString()
setMessage('')
setError(err)
return {
status: 'failed',
message: err,
}
}
}
return {
verifyConfirmationCode,
sendConfirmationCode,
message,
error,
}
}
export default useAccount