0% found this document useful (0 votes)
4 views

Edit Pro

Uploaded by

howlettreginald
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Edit Pro

Uploaded by

howlettreginald
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 7

import { useAuth } from "@/hooks/useAuth";

import { useNavigate, useParams } from "react-router-dom";


import { useEffect, useState } from "react";
import useNotification from "@/hooks/useNotification";
import useFetchData from "@/hooks/useFetchData";

const EditProfile = () => {


const { notify } = useNotification();
const navigate = useNavigate();
const { userId } = useParams();
const { user } = useAuth();
const { token } = useAuth();
const { fetchData } = useFetchData();
const [errors, setErrors] = useState({});
const [formData, setFormData] = useState({
name: "",
lastname: "",
birthDate: "",
gender: "",
nationality: "",
phone: "",
cellphone: "",
dni: "",
email: "",
password: "",
});

function isOwnProfile() {
return user.id == userId;
}

useEffect(() => {
const fetchUserDetails = async () => {
try {
const response = await
fetchData(`/api/user/profile/${userId}/details`, {
method: 'GET',
});

if (response && response.data) {


setFormData({
name: response.data.name || "",
lastname: response.data.lastname || "",
birthDate: new
Date(response.data.birthDate).toISOString().split('T')[0] || "",
gender: response.data.gender || "",
nationality: response.data.nationality || "",
phone: response.data.phone || "",
cellphone: response.data.cellphone || "",
dni: response.data.dni || "",
email: response.data.email || "",
});
} else {
console.error('Error al obtener datos del usuario:', response);
}
} catch (error) {
console.error('Error al cargar los datos:', error);
}
};
fetchUserDetails();
}, [userId]);

const handleChange = (e) => {


const { name, value } = e.target;
setFormData({
...formData,
[name]: value,
});
};

const validate = () => {


const newErrors = {};

if (!formData.name || formData.name.length > 50) {


newErrors.name = "El nombre es obligatorio y debe tener hasta 50
caracteres";
}

if (!formData.lastname || formData.lastname.length > 50) {


newErrors.lastname = "El apellido es obligatorio y debe tener hasta 50
caracteres";
}

if (formData.dni && !/^[0-9]{7,8}$/.test(formData.dni)) {


newErrors.dni = "El DNI debe tener entre 7 y 8 dígitos";
}

if (formData.phone && formData.phone.length > 15) {


newErrors.phone = "El teléfono debe tener hasta 15 caracteres";
}

if (formData.cellphone && formData.cellphone.length > 15) {


newErrors.cellphone = "El celular debe tener hasta 15 caracteres";
}

if (formData.birthDate && !/^\d{4}-\d{2}-\d{2}$/.test(formData.birthDate))


{
newErrors.birthDate = "La fecha debe tener el formato DD-MM-AAAA";
}

setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};

const validateEmail = () => {


const newErrors = {};

if (!formData.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)){


newErrors.email = "Ingrese un email válido";
}

if (!formData.password || formData.password.length < 6) {


newErrors.password = "Ingrese su contraseña";
}

setErrors(newErrors);
return Object.keys(newErrors).length === 0;
}

const handleEmailChange = async (e) => {

e.preventDefault();
if (!validateEmail()) return;

const data = new FormData();


data.append('email', formData.email);
data.append('password', formData.password);

try {
const response = await
fetch(`${import.meta.env.VITE_API_URL}/api/user/profile/${userId}/edit/email`, {
method: "PUT",
headers: {
'Authorization': `${token}`
},
body: data,
});

if (response.ok) {
notify("Perfil actualizado correctamente", "success");
navigate(`/profile/${userId}`);
} else {
notify("Hubo un problema al actualizar el perfil", "error");
console.error("Error al actualizar el perfil:", response);
}
} catch (error) {
console.error("Error en la solicitud:", error);
notify("Error al enviar la solicitud", "error");
}
}

const handleSubmit = async (e) => {

e.preventDefault();
if (!validate()) return;

const data = new FormData();


data.append('name', formData.name);
data.append('lastname', formData.lastname);
data.append('gender', formData.gender);
data.append('nationality', formData.nationality);
data.append('phone', formData.phone);
data.append('cellphone', formData.cellphone);
data.append('dni', formData.dni);
data.append('birthDate', new Date(formData.birthDate).toISOString());

try {
const response = await
fetch(`${import.meta.env.VITE_API_URL}/api/user/profile/${userId}/edit`, {
method: "PUT",
headers: {
'Authorization': `${token}`
},
body: data,
});
if (response.ok) {
notify("Perfil actualizado correctamente", "success");
navigate(`/profile/${userId}`);
} else {
notify("Hubo un problema al actualizar el perfil", "error");
console.error("Error al actualizar el perfil:", response);
}
} catch (error) {
console.error("Error en la solicitud:", error);
notify("Error al enviar la solicitud", "error");
}
};

return (
<div className="flex flex-col items-center justify-center bg-gray-100 py-10
px-4">
<div className="max-w-2xl w-full bg-white rounded-lg shadow-md">
<div className="text-center py-6">
<h1 className="text-3xl font-bold text-gray-800">Editar
Perfil</h1>
{isOwnProfile() ? (
<div>
<p className="text-sm text-gray-500">Modifica tus
datos</p>
</div>
) : (
<p className="text-sm text-gray-500">{userdata.name + " " +
userdata.lastname}</p>
)}
</div>
<hr className="border-gray-300"/>
<form onSubmit={handleSubmit} className="bg-gray-50 py-6 px-8
space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Nombre:</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.name && <p className="text-red-500 text-
sm">{errors.name}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Apellido:</label>
<input
type="text"
name="lastname"
value={formData.lastname}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.lastname && <p className="text-red-500 text-
sm">{errors.lastname}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">DNI:</label>
<input
type="text"
name="dni"
value={formData.dni}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.dni && <p className="text-red-500 text-
sm">{errors.dni}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Fecha de Nacimiento:</label>
<input
type="date"
name="birthDate"
value={formData.birthDate}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.birthDate && <p className="text-red-500 text-
sm">{errors.birthDate}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Teléfono:</label>
<input
type="text"
name="phone"
value={formData.phone}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.phone && <p className="text-red-500 text-
sm">{errors.phone}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Celular:</label>
<input
type="text"
name="cellphone"
value={formData.cellphone}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
{errors.cellphone && <p className="text-red-500 text-
sm">{errors.cellphone}</p>}
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Nacionalidad:</label>
<input
type="text"
name="nationality"
value={formData.nationality}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
/>
</div>
<div className="flex flex-col">
<label className="block text-gray-700 font-semibold mb-
1">Género:</label>
<select
type="text"
name="gender"
value={formData.gender}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
>
<option value="">Seleccione</option>
<option value="Masculino">Masculino</option>
<option value="Femenino">Femenino</option>
</select>
</div>
</div>
<div className="flex justify-end gap-3 mt-6">
<button
type="submit"
className="w-full py-3 px-6 rounded-md text-white
hover:bg-[#6d0d1d] bg-[#8e1826] hover:scale-105 hover:shadow-lg transition-all
font-bold text-lg"
>
Guardar
</button>
<button
type="button"
onClick={() => navigate(-1)}
className="w-full py-3 px-6 rounded-md text-white bg-
gray-500 hover:bg-gray-600 hover:scale-105 hover:shadow-lg transition-all font-bold
text-lg"
>
Cancelar
</button>
</div>
</form>
</div>
{/* Cambio de email */}
<div className="max-w-2xl w-full bg-white rounded-lg shadow-md mt-8">
<div className="text-center py-6">
<h2 className="text-2xl font-semibold text-gray-800">Modificar
Email</h2>
<p className="text-sm text-gray-500">Debes ingresar la
contraseña para confirmar el cambio</p>
</div>
<hr className="border-gray-300"/>
<div className="py-6 px-8">
<form onSubmit={handleEmailChange} className="bg-gray-50 py-6
px-8 space-y-4">
<div className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1">Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
required
/>
{errors.email && <p className="text-red-500 text-
sm">{errors.email}</p>}
</div>
<div className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1">Contraseña:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
className="border border-gray-300 rounded-md p-2"
required
/>
{errors.password && <p className="text-red-500 text-
sm">{errors.password}</p>}
</div>
<div className="flex justify-end gap-3 mt-6">
<button
type="submit"
className="w-full py-3 px-6 rounded-md text-white
hover:bg-[#6d0d1d] bg-[#8e1826] hover:scale-105 hover:shadow-lg transition-all
font-bold text-lg"
>
Confirmar
</button>
</div>
</form>
</div>
</div>
</div>

);
};

export default EditProfile;

You might also like