feat: upload photo

This commit is contained in:
Vinicius Souza 2024-11-07 15:35:00 +00:00
parent 065b7fb1a4
commit f0f1567297
2 changed files with 39 additions and 2 deletions

View file

@ -8,6 +8,8 @@ import { Controller, useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import { api } from '@services/api';
import { AppError } from '@utils/AppError';
import { slug } from '@utils/Slug';
import { useAuth } from '@hooks/useAuth';
@ -16,7 +18,6 @@ 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;
@ -150,7 +151,33 @@ export function Profile() {
});
}
setUserPhoto(photoURI);
const fileExtension = photoSelection.assets[0].uri.split('.').pop();
const photoFile = {
name: `${slug(user.name)}.${fileExtension}`.toLowerCase(),
uri: photoSelection.assets[0].uri,
type: `${photoSelection.assets[0].type}/${fileExtension}`,
} as any;
const userPhotoUploadForm = new FormData();
userPhotoUploadForm.append('avatar', photoFile);
await api.patch('/users/avatar', userPhotoUploadForm, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
toast.show({
placement: 'top',
render: ({ id }) => (
<ToastMessage
id={id}
title="Foto do perfil atualizada com sucesso!"
action="success"
onClose={() => toast.close(id)}
/>
),
});
}
} catch (error) {
console.error(error);

10
src/utils/Slug.ts Normal file
View file

@ -0,0 +1,10 @@
export function slug(str: string): string {
return str
.normalize('NFD') // Normalize accented characters to decomposed form
.replace(/[\u0300-\u036f]/g, '') // Remove diacritic marks (accents)
.toLowerCase() // Convert to lowercase
.replace(/[^a-z0-9\s-]/g, '') // Remove non-alphanumeric characters except spaces and hyphens
.trim() // Remove leading and trailing spaces
.replace(/\s+/g, '-') // Replace spaces with hyphens
.replace(/-+/g, '-'); // Replace multiple hyphens with a single hyphen
}