Merge pull request 'fix(perfil) corregir o bug do avatar no perfil de adiministrador' (#75) from feature/ajusAvatar into develop

Reviewed-on: RiseUP/riseup-squad20#75
This commit is contained in:
Jonasbomfim 2025-11-09 00:44:50 +00:00
commit 9290498f7b
3 changed files with 70 additions and 4 deletions

View File

@ -51,7 +51,7 @@ interface UserProfile {
export default function PerfilPage() {
const router = useRouter();
const { user: authUser } = useAuth();
const { user: authUser, updateUserProfile } = useAuth();
const [userInfo, setUserInfo] = useState<UserProfile | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
@ -229,6 +229,31 @@ export default function PerfilPage() {
} : null,
} : null
);
// Also update global auth profile so header/avatar updates immediately
try {
if (typeof updateUserProfile === 'function') {
updateUserProfile({
// Persist common keys used across the app
foto_url: editingData.avatar_url || undefined,
telefone: editingData.phone || undefined
});
} else {
// Fallback: try to persist directly to localStorage so next reload shows it
try {
const raw = localStorage.getItem('auth_user')
if (raw) {
const u = JSON.parse(raw)
u.profile = u.profile || {}
if (editingData.avatar_url) { u.profile.foto_url = editingData.avatar_url; u.profile.avatar_url = editingData.avatar_url }
if (editingData.phone) u.profile.telefone = editingData.phone
localStorage.setItem('auth_user', JSON.stringify(u))
}
} catch (_e) {}
}
} catch (err) {
console.warn('[PERFIL] Falha ao sincronizar profile global:', err)
}
} catch (err: any) {
console.error('[PERFIL] Erro ao salvar:', err);
}
@ -591,7 +616,25 @@ export default function PerfilPage() {
<UploadAvatar
userId={userInfo.user.id}
currentAvatarUrl={editingData.avatar_url || userInfo.profile?.avatar_url || "/avatars/01.png"}
onAvatarChange={(newUrl) => setEditingData({...editingData, avatar_url: newUrl})}
onAvatarChange={(newUrl) => {
setEditingData({...editingData, avatar_url: newUrl})
try {
if (typeof updateUserProfile === 'function') {
updateUserProfile({ foto_url: newUrl })
} else {
const raw = localStorage.getItem('auth_user')
if (raw) {
const u = JSON.parse(raw)
u.profile = u.profile || {}
u.profile.foto_url = newUrl
u.profile.avatar_url = newUrl
localStorage.setItem('auth_user', JSON.stringify(u))
}
}
} catch (err) {
console.warn('[PERFIL] erro ao persistir avatar no auth_user localStorage', err)
}
}}
userName={editingData.full_name || userInfo.profile?.full_name || "Usuário"}
/>
</div>

View File

@ -336,6 +336,26 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}
}, [user?.userType, token, clearAuthData])
// Allow updating the in-memory user profile and persist to localStorage.
const updateUserProfile = useCallback((partial: Partial<UserData['profile']>) => {
try {
setUser((prev) => {
if (!prev) return prev
const next = { ...prev, profile: { ...(prev.profile || {}), ...(partial || {}) } }
try {
if (typeof window !== 'undefined') {
localStorage.setItem(AUTH_STORAGE_KEYS.USER, JSON.stringify(next))
}
} catch (e) {
console.warn('[AUTH] Falha ao persistir user atualizado no localStorage:', e)
}
return next
})
} catch (err) {
console.warn('[AUTH] updateUserProfile erro:', err)
}
}, [])
// Refresh token memoizado (usado pelo HTTP client)
const refreshToken = useCallback(async (): Promise<boolean> => {
// Esta função é principalmente para compatibilidade
@ -350,8 +370,9 @@ export function AuthProvider({ children }: { children: ReactNode }) {
token,
login,
logout,
refreshToken
}), [authStatus, user, token, login, logout, refreshToken])
refreshToken,
updateUserProfile
}), [authStatus, user, token, login, logout, refreshToken, updateUserProfile])
// Inicialização única
useEffect(() => {

View File

@ -51,6 +51,8 @@ export interface AuthContextType {
login: (email: string, password: string, userType: UserType) => Promise<boolean>
logout: () => Promise<void>
refreshToken: () => Promise<boolean>
// Merge partial profile into the stored user (client-side convenience)
updateUserProfile?: (partial: Partial<UserData['profile']>) => void
}
export interface AuthStorageKeys {