From cc1a3728e507fb2f2b03f99a5c8f1fe6f30c76c8 Mon Sep 17 00:00:00 2001 From: Joseph D'Souza Date: Wed, 11 Feb 2026 13:17:38 +0100 Subject: [PATCH] add manager for edit profile service --- mobile/src/hooks/useProfileManager.ts | 91 +++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 mobile/src/hooks/useProfileManager.ts diff --git a/mobile/src/hooks/useProfileManager.ts b/mobile/src/hooks/useProfileManager.ts new file mode 100644 index 0000000..61e4783 --- /dev/null +++ b/mobile/src/hooks/useProfileManager.ts @@ -0,0 +1,91 @@ +import { useState } from 'react'; +import { Alert } from 'react-native'; +import { useNavigation } from '@react-navigation/native'; +import * as ImagePicker from 'expo-image-picker'; +import { useAuthStore } from '../store/useAuthStore'; +import { authService } from '../services/api'; + +export const useProfileManager = () => { + const navigation = useNavigation(); + const { user, updateUser } = useAuthStore(); + + const [firstName, setFirstName] = useState(user?.user?.first_name || ''); + const [lastName, setLastName] = useState(user?.user?.last_name || ''); + const [phone, setPhone] = useState(user?.user?.phone || ''); + const [address, setAddress] = useState(user?.user?.address || ''); + const [avatar, setAvatar] = useState(user?.user?.avatar || null); + const [loading, setLoading] = useState(false); + + const pickImage = async () => { + const result = await ImagePicker.launchImageLibraryAsync({ + mediaTypes: 'images', + allowsEditing: true, + aspect: [1, 1], + quality: 0.5, + }); + + if (!result.canceled) { + setAvatar(result.assets[0].uri); + } + }; + + const handleSave = async () => { + setLoading(true); + try { + let updatedAvatarUrl = user?.user?.avatar; + + // Upload avatar if it has changed + if (avatar && avatar !== user?.user?.avatar) { + const avatarResult = await authService.uploadAvatar(avatar); + if (avatarResult.ok && avatarResult.data.data.avatar) { + updatedAvatarUrl = avatarResult.data.data.avatar; + } else { + Alert.alert('Warning', 'Failed to upload new profile picture, but proceeding with other updates.'); + } + } + + const updates = { + first_name: firstName, + last_name: lastName, + phone, + address, + }; + + const result = await authService.updateProfile(updates); + + if (result.ok) { + const finalUserData = { + ...(result.data.data || result.data), + avatar: updatedAvatarUrl + }; + updateUser(finalUserData); + + Alert.alert('Success', 'Profile updated successfully', [ + { text: 'OK', onPress: () => navigation.goBack() } + ]); + } else { + Alert.alert('Error', result.message || 'Failed to update profile'); + } + } catch (error) { + console.error(error); + Alert.alert('Error', 'An unexpected error occurred.'); + } finally { + setLoading(false); + } + }; + + return { + loading, + avatar, + firstName, + lastName, + phone, + address, + setFirstName, + setLastName, + setPhone, + setAddress, + pickImage, + handleSave, + }; +};