diff --git a/src/screens/Profile.tsx b/src/screens/Profile.tsx index 6e59230..510ca10 100644 --- a/src/screens/Profile.tsx +++ b/src/screens/Profile.tsx @@ -7,6 +7,8 @@ import * as yup from 'yup'; import { Controller, useForm } from 'react-hook-form'; import { yupResolver } from '@hookform/resolvers/yup'; +import { api } from '@services/api'; + import { useAuth } from '@hooks/useAuth'; import { Button } from '@components/Button'; @@ -14,6 +16,7 @@ import { Input } from '@components/Input'; import { ScreenHeader } from '@components/ScreenHeader'; import { UserPhoto } from '@components/UserPhoto'; import { ToastMessage } from '@components/ToastMessage'; +import { AppError } from '@utils/AppError'; type ProfileForm = { name: string; @@ -37,11 +40,16 @@ const profileSchema = yup.object({ .oneOf([yup.ref('new_password'), null], 'Senhas não coincidem.') .when('new_password', { is: (field: any) => field, - then: yup.string().nullable().required('Senhas não coincidem'), + then: yup + .string() + .nullable() + .required('Senhas não coincidem') + .transform((value) => (!!value ? value : null)), }), }); export function Profile() { + const [isUpdating, setIsUpdating] = useState(false); const [userPhoto, setUserPhoto] = useState('https://i.pravatar.cc/200'); const toast = useToast(); @@ -64,9 +72,41 @@ export function Profile() { async function handleProfileUpdate(data: ProfileForm) { try { - console.debug('handleProfileUpdate =>', data); + setIsUpdating(true); + + await api.put('/users', { + name: data.name, + password: data.new_password, + old_password: data.old_password, + }); + toast.show({ + placement: 'top', + render: ({ id }) => ( + toast.close(id)} + /> + ), + }); } catch (error) { - throw error; + const isAppError = error instanceof AppError; + const title = isAppError ? error.message : 'Não foi possível atualizar.'; + toast.show({ + placement: 'top', + render: ({ id }) => ( + toast.close(id)} + /> + ), + }); + } finally { + setIsUpdating(false); } } @@ -196,7 +236,12 @@ export function Profile() { )} /> -