0% found this document useful (0 votes)
5 views9 pages

Lala

Uploaded by

howlettreginald
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Lala

Uploaded by

howlettreginald
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 9

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

import { useEffect, useRef, useState } from "react";


import { useParams, useNavigate } from "react-router-dom";
import useNotification from "@/hooks/useNotification";
import useFetchData from "@/hooks/useFetchData";
import { Skeleton } from "@/components/ui/skeleton"

const EditProfile = () => {


const { userId } = useParams();
const { user } = useAuth(); // No utilizas token, así que lo omitimos
const [userdata, setUserData] = useState(null);
const navigate = useNavigate();
const { notify } = useNotification();
const { fetchData } = useFetchData();
const requestFailed = useRef(false);
const [error, setError] = useState(false); // Estado para manejar errores
const [isEmailModified, setIsEmailModified] = useState(false);
const [isPasswordModified, setIsPasswordModified] = useState(false);
const [isBirthDateModified, setIsBirthDateModified] = useState(false);
const [isStudentModified, setIsStudentModified] = useState(false);
const [isProfessionalDataModified, setIsProfessionalDataModified] =
useState(false);
function isOwnProfile() {
return user.id == userId;
}

const fetchUser = async () => {


const { data, error } = await fetchData(`/api/user/professional-student/$
{userId}`, {
method: 'GET',
});
console.log("Fetched data.datavalues:", data); // Debugging
if (data) {
setUserData(data);
console.log("Scheduled setUserData with:", data);
} else if (error) {
notify({
type: error.type || "error",
message: error.message,
});

if (error.status === 401) {


navigate("/login");
}
requestFailed.current = true;
}
}; // Closing the fetchUser function

useEffect(() => {
if (!userdata && !error) {
fetchUser();
}
}, [userdata, error, fetchUser]);

useEffect(() => {
console.log("Updated userdata:", userdata); // Track updates
}, [userdata]);

const handleSaveChanges = async () => {


//antes de llamar al endpoint verifico que no se hayan dejado campos
obligatorios vacios
if(userdata.userProfile.email === "" || userdata.userProfile.name === "" ||
userdata.userProfile.lastname === "" || userdata.userProfile.birthDate === "" ||
userdata.userProfile.nationality === "" || userdata.userProfile.gender === "" ||
userdata.userProfile.password === ""){
notify({
type: "error",
message: "Faltan ingresar campos obligatorios"
});
return;
}
if (!isPasswordModified) {
notify({
type: "error",
message: "La contraseña es obligatoria",
});
return;
}

//verifico que el email tenga el formato correcto [email protected] si fue modificado


if(isEmailModified && !userdata.userProfile.email.match(/^[^\s@]+@[^\s@]+\.
[^\s@]+$/) ){
notify({
type: "error",
message: "El email ingresado no tiene un formato válido"
});
return;
}

//verifico que la fecha de nacimiento no sea futura si fue modificado


if(isBirthDateModified && new Date(userdata.userProfile.birthDate) > new
Date()){
notify({
type: "error",
message: "La fecha de nacimiento no puede ser mayor a la actual"
});
return;
}

//verifico que la contraseña tenga como minimo 6 caracteres si fue


modificado
if(isPasswordModified && userdata.userProfile.password.length < 6 ){
notify({
type: "error",
message: "La contraseña debe tener al menos 6 caracteres"
});
return;
}

if(isStudentModified && (userdata.userProfile.student.legajo === "" ||


userdata.userProfile.student.university === "")){
notify({
type: "error",
message: "La información de estudiante es obligatoria"
});
return;
}
if(isProfessionalDataModified &&
userdata.userProfile.professionalData.matricula === ""){
notify({
type: "error",
message: "La información profesional es obligatoria"
});
return;
}

const { data, error } = await fetchData(`/api/user/edit/${userId}`, {


method: 'POST',
body: { userdata },
});

console.log("los datos actualizados en el front:", data)

if (data) {
notify({
type: 'success',
message: 'Cambios guardados exitosamente',
});
} else if (error) {
notify({
type: error.type || "error",
message: error.message,
});
}
navigate(`/profile/${userId}`);
};

if (!userdata && !requestFailed.current) {


return (
<>
<div className='flex flex-col items-center justify-center'>
<hr className='mt-10 border-gray-700 w-1/2 mb-2' />
<Skeleton className="h-10 w-1/2 mb-4" />
<hr className='border-gray-700 w-1/2' />
</div>
<div className="flex justify-center items-center">
<div className='p-6 bg-gray-100 rounded-lg shadow-md md:my-20
w-1/2 md:w-full'>
<Skeleton className='h-8 w-1/2 mb-4' />
<Skeleton className='h-6 w-1/3 mb-4' />
<Skeleton className='h-4 w-full mb-2' />
<Skeleton className='h-4 w-full mb-2' />
<Skeleton className='h-4 w-full mb-2' />
<Skeleton className='h-4 w-1/2 mb-4' />
<Skeleton className='h-6 w-1/4 mb-4' />
<Skeleton className='h-6 w-1/4 mb-4' />
<Skeleton className='h-6 w-1/4 mb-4' />
<Skeleton className='h-8 w-1/3 mb-4' />
<Skeleton className='h-8 w-1/3 mb-4' />
</div>
</div>
</>
);
} else if (requestFailed.current) {
return (
<div className="flex justify-center items-center h-screen">
<p className="text-gray-700">No se pudo cargar la información del
usuario.</p>
</div>
);
}
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" />

{/* Aquí comienza el formulario de edición de perfil */}

<div className="bg-gray-50 py-6 px-8">


<ul className="bg-gray-50 py-6 px-8">
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Email:</strong></label>
<input
type="email"
value={userdata.userProfile.email}
onChange={(e) => {
setIsEmailModified(true);
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile, email:
e.target.value },
}));
}}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>

<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Nombre:</strong></label>
<input
type="text"
value={userdata.userProfile.name}
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile, name:
e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>

<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Apellido:</strong></label>
<input
type="text"
value={userdata.userProfile.lastname}
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile,
lastname: e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>DNI:</strong></label>
<input
text="text"
value={userdata.userProfile.dni}
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile, dni:
e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Teléfono:</strong></label>
<input
type="text"
value={userdata.userProfile.phone || ""}
placeholder="Ingresar número de teléfono"
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile, phone:
e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Celular:</strong></label>
<input
type="text"
value={userdata.userProfile.cellphone || ""}
placeholder="Ingresar numero de celular"
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile,
cellphone: e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Fecha de nacimiento:</strong></label>
<input
type="date"
value={userdata.userProfile.birthDate.split("T")
[0]}
onChange={(e) => {
setIsBirthDateModified(true);
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile,
birthDate: e.target.value },
}))
}}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Nacionalidad:</strong></label>
<input
type="text"
value={userdata.userProfile.nationality}
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile,
nationality: e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Género:</strong></label>
<select
type="text"
value={userdata.userProfile.gender}
onChange={(e) =>
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile, gender:
e.target.value },
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
>
<option value="No asignado" disabled>Seleccionar
género</option>
<option value="Masculino">Masculino</option>
<option value="Femenino">Femenino</option>
<option value="Femenino">Otro</option>
</select>
</li>
{/*<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Tipo de perfil:</strong></label>
<select
type="text"
value={userdata.userProfile.type_profile|| "No
asignado"}
onChange={(e) =>
setUserData((prev) => ({
...prev, //copia el estado previo
userProfile: { ...prev.userProfile,
type_profile: e.target.value }, //cambia el valor de profile_type dentro de
userProfile
}))
}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
>
<option value="No asignado" disabled>Seleccionar
tipo de perfil</option>
<option value="profesional">Profesional</option>
<option value="estudiante">Estudiante</option>
<option value="comunidad">Comunidad</option>
</select>
</li>*/}
<li className="mb-4">
<label className="block text-gray-700 font-semibold mb-
1"><strong>Contraseña:</strong></label>
<input
type="password"
placeholder="Ingresar nueva contraseña"
onChange={(e) => {
setIsPasswordModified(true);
setUserData((prev) => ({
...prev,
userProfile: { ...prev.userProfile,
password: e.target.value },
}))
}}
className="w-full p-3 border border-gray-300
rounded-lg focus:ring focus:ring-blue-200 bg-gray-50"
/>
</li>
</ul>
</div>
{userdata.userProfile.student && (
<>
<h2 className="text-2xl mt-5">Información de
estudiante</h2>
<div className="bg-gray-200 w-full md:w-1/4 text-center
md:rounded-lg">
<ul className="space-y-2 p-2">
<li>
<label><strong>Legajo:</strong></label>
<input
type="text"
value={userdata.userProfile.student.legajo}
onChange={(e) => {
setIsStudentModified(true);
setUserData((prev) => ({
...prev,
userProfile: {
...prev.userProfile,
student: {
...prev.userProfile.student
,
legajo: e.target.value,
},
},
}))
}}
className="bg-gray-50 border border-gray-
300 text-gray-900 rounded-lg w-full p-1"
/>
</li>
<li>
<label><strong>Cátedra:</strong></label>
<input
type="text"

value={userdata.userProfile.student.university}
onChange={(e) => {
setIsStudentModified(true);
setUserData((prev) => ({
...prev,
userProfile: {
...prev.userProfile,
student: {
...prev.userProfile.student
,
university: e.target.value,
},
},
}))
}}
className="bg-gray-50 border border-gray-
300 text-gray-900 rounded-lg w-full p-1"
/>
</li>
</ul>
</div>
</>
)}
{userdata.userProfile.professionalData && (
<>
<h2 className="text-2xl mt-5">Información profesional</h2>
<div className="bg-gray-200 w-full md:w-1/4 text-center
md:rounded-lg">
<ul className="space-y-2 p-2">
<li>
<label><strong>Matrícula:</strong></label>
<input
type="text"

value={userdata.userProfile.professionalData.matricula}
onChange={(e) => {
setIsProfessionalDataModified(true);
setUserData((prev) => ({
...prev,
userProfile: {
...prev.userProfile,
professionalData: {
...prev.userProfile.profess
ionalData,
matricula: e.target.value,
},
},
}))
}}
className="bg-gray-50 border border-gray-
300 text-gray-900 rounded-lg w-full p-1"
/>
</li>
</ul>
</div>
</>
)}
<button style={{ backgroundColor: '#6d0d1d', color: 'white' }}
className="hover:bg-gray-700 font-bold py-2 px-4 rounded mt-5"
onClick={handleSaveChanges}>
Guardar cambios
</button>
</div>
</div>
</>
);

};

export default EditProfile;

You might also like