|
| 1 | +import { isLogIn } from '@/apis/authApis'; |
| 2 | +import updateUser from '@/apis/updateUserApi'; |
| 3 | +import { useChangePasswordState } from '@/stores/changePasswordStore'; |
| 4 | +import supabase from '@/supabase'; |
| 5 | +import { LooseValidation, ValidateProcessor } from '@/utils/authUtils'; |
| 6 | +import { useMutation } from '@tanstack/react-query'; |
| 7 | +import { useRef, useState } from 'react'; |
| 8 | +import { useNavigate } from 'react-router-dom'; |
| 9 | + |
| 10 | +interface DialogElement { |
| 11 | + openModal: () => void; |
| 12 | + closeModal: () => void; |
| 13 | +} |
| 14 | + |
| 15 | +const useUpdateUser = () => { |
| 16 | + const { mutate, isPending } = useMutation({ |
| 17 | + mutationKey: ['updateUser'], |
| 18 | + mutationFn: updateUser, |
| 19 | + }); |
| 20 | + const [dialogMessage, setDialogMessage] = useState(''); |
| 21 | + const { password } = useChangePasswordState(); |
| 22 | + const dialogRef = useRef<DialogElement | null>(null); |
| 23 | + const navigate = useNavigate(); |
| 24 | + |
| 25 | + const validator = new ValidateProcessor(new LooseValidation()); |
| 26 | + |
| 27 | + const onClick = () => { |
| 28 | + if (!validator.isValidPassword(password)) { |
| 29 | + setDialogMessage('유효하지 않은 패스워드 입니다.'); |
| 30 | + dialogRef.current?.openModal(); |
| 31 | + } |
| 32 | + |
| 33 | + mutate(password, { |
| 34 | + onSuccess: async () => { |
| 35 | + const { session } = await isLogIn(); |
| 36 | + if (session) { |
| 37 | + await supabase.auth.signOut(); |
| 38 | + } |
| 39 | + navigate('/login'); |
| 40 | + }, |
| 41 | + onError: (e) => { |
| 42 | + setDialogMessage(e.message); |
| 43 | + dialogRef.current?.openModal(); |
| 44 | + }, |
| 45 | + }); |
| 46 | + }; |
| 47 | + return { |
| 48 | + isPending, |
| 49 | + onClick, |
| 50 | + dialogRef, |
| 51 | + dialogMessage, |
| 52 | + }; |
| 53 | +}; |
| 54 | + |
| 55 | +export default useUpdateUser; |
0 commit comments