Skip to content

Commit

Permalink
fixing profile update
Browse files Browse the repository at this point in the history
  • Loading branch information
amiparadis250 committed Jul 16, 2024
1 parent 778cc03 commit de094fa
Show file tree
Hide file tree
Showing 4 changed files with 96 additions and 26 deletions.
99 changes: 79 additions & 20 deletions src/app/(profile)/profile-edit/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,34 @@ import React, { useEffect, useState, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { AppDispatch, RootState } from '@/redux/store';
import { getUserProfile, updateUserProfile } from '@/redux/slices/profileSlice';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import InputBox from '@/components/InputBox';

import { toast } from 'react-toastify';
import { showToast } from '@/helpers/toast';
import { useForm, SubmitHandler, useWatch } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

import updateSchema from '@/validations/userProfileSchema';
import { useRouter } from 'next/navigation';
import type { z } from 'zod';

import { zodResolver } from '@hookform/resolvers/zod';

import InputBox from '@/components/InputBox';
import UpdatePasswords from '@/components/updatepassword';
import Header from '@/components/Header';
import Footer from '@/components/Footer';
import { User, Cake, Award } from 'lucide-react'
type FormSchemaType = z.infer<typeof updateSchema>;

const UserProfileForm: React.FC = () => {
const route = useRouter();
const [showlModal, setShowmodal] = useState(false);
const dispatch = useDispatch<AppDispatch>();
const { user, loading, error } = useSelector(
(state: RootState) => state.userProfile,
);

const handleshow = () => {
setShowmodal(!showlModal);
};
const {
register,
handleSubmit,
Expand All @@ -34,6 +43,7 @@ const UserProfileForm: React.FC = () => {
firstName: '',
lastName: '',
phone: '',
address:'',
birthDate: '',
preferredLanguage: '',
whereYouLive: '',
Expand Down Expand Up @@ -68,7 +78,7 @@ const UserProfileForm: React.FC = () => {
}, [user, setValue]);

const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files.length === 1) {
if (e.target.files && e.target?.files?.length === 1) {
const file = e.target.files[0];
setImageFile(file);
const reader = new FileReader();
Expand All @@ -83,40 +93,53 @@ const UserProfileForm: React.FC = () => {
fileInputRef.current?.click();
};

const onSubmit: SubmitHandler<FormSchemaType> = async (data) => {
if (!imageFile && !profileImage) {
toast.error(
'Please select a profile image before updating your profile.',
);
return;
const getExistingImage = async (): Promise<File | null> => {
if (!user?.User?.profileImage) return null;

try {
const response = await fetch(user.User.profileImage);
const blob = await response.blob();
return new File([blob], 'profile_image.jpg', { type: blob.type });
} catch (error) {
console.error('Error fetching existing image:', error);
return null;
}
};

const onSubmit: SubmitHandler<FormSchemaType> = async (data) => {
const formDataToSend = new FormData();

Object.entries(data).forEach(([key, value]) => {
formDataToSend.append(key, value as string);
});

let imageToUpload: File | null = null;

if (imageFile) {
formDataToSend.append('profileImage', imageFile);
imageToUpload = imageFile;
} else {
imageToUpload = await getExistingImage();
}

if (imageToUpload) {
formDataToSend.append('profileImage', imageToUpload);
}

try {
setIsLoading(true);
const response = await dispatch(updateUserProfile(formDataToSend));
setIsLoading(false);
if (updateUserProfile.fulfilled.match(response)) {
// Update only the User value in localStorage
const currentProfile = JSON.parse(
localStorage.getItem('profile') || '{}',
);
if (response.payload && response.payload.User) {
currentProfile.User = response.payload.User;
console.log('currentProfile', currentProfile);
localStorage.setItem('profile', JSON.stringify(currentProfile));
}

toast.success('Profile updated successfully');
route.push('/profile');
} else if (updateUserProfile.rejected.match(response)) {
const errorMessage: any =
response.payload &&
Expand Down Expand Up @@ -147,9 +170,26 @@ const UserProfileForm: React.FC = () => {
if (!user) {
return <div>No user data available. Please try refreshing the page.</div>;
}

const getCurrentDate = () => {
const today = new Date();
const year = today.getFullYear() - 10;
const month = String(today.getMonth() + 1).padStart(2, '0');
const day = String(today.getDate()).padStart(2, '0');
return `${year}-${month}-${day}`;
};
function formatDate(dateString: string) {
// Parse the date string into a Date object
const date = new Date(dateString);
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, '0');
const day = date.getDate().toString().padStart(2, '0');
const formattedDate = `${day}-${month}-${year}`;

return formattedDate;
}

return (
<div className="flex flex-col min-h-screen bg-gray-100">
<div className="flex flex-col min-h-screen w-full">
<Header />
<main className="flex-grow p-4 sm:p-6">
<div className="max-w-5xl mx-auto bg-white rounded-lg shadow-md">
Expand All @@ -162,6 +202,10 @@ const UserProfileForm: React.FC = () => {
src={profileImage}
alt="Profile"
onClick={handleImageClick}
onError={(e) => {
e.currentTarget.src = '/unknown.jpg';
}}

/>
<input
type="file"
Expand Down Expand Up @@ -266,6 +310,14 @@ const UserProfileForm: React.FC = () => {
</svg>
{watchedValues.phone || 'Contact Number'}
</li>
<li>
<button
onClick={() => setShowmodal(!showlModal)}
className="cursor-pointer p-2 text-blue-500 hover:text-blue-600 hover:font-semibold duration-200 "
>
Update Password
</button>
</li>
</ul>
</aside>

Expand Down Expand Up @@ -302,15 +354,16 @@ const UserProfileForm: React.FC = () => {
placeholder="Birth date"
{...register('birthDate')}
error={errors.birthDate?.message}

max={getCurrentDate()}
/>
</div>
<div className="mb-4">
<InputBox
nameuse="Address"
type="text"
placeholder="Address"
{...register('whereYouLive')}
error={errors.whereYouLive?.message}
error ={errors.address?.message}
/>
</div>
<div className="mb-4">
Expand Down Expand Up @@ -349,10 +402,11 @@ const UserProfileForm: React.FC = () => {
</div>
<div className="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
<button
onClick={() => route.back()}
type="button"
className="w-full sm:w-1/2 bg-white text-gray-700 border border-gray-300 px-16 py-2 rounded hover:bg-gray-100 transition duration-300"
>
<a href="/profile">Cancel</a>
<a>Cancel</a>
</button>
<button
type="submit"
Expand All @@ -370,6 +424,11 @@ const UserProfileForm: React.FC = () => {
</div>
</div>
</main>
<div className=''>
<UpdatePasswords handleshow={handleshow} showlModal={showlModal}/>
</div>


<Footer />
</div>
);
Expand Down
8 changes: 4 additions & 4 deletions src/components/profile/About.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,19 +27,19 @@ function About() {
const items: any = [
{
icon: <Cake className="text-green-500" />,
details: `${user.User?.birthDate}`,
details: `${user.User?.birthDate || 'YYYY-MM-DD'} `,
},
{
icon: <FaLocationDot className="text-green-500" />,
details: `${user.User?.whereYouLive}`,
details: `${user.User?.whereYouLive || "Where You Live"}`,
},
{
icon: <FaEnvelope className="text-green-500" />,
details: `${user.User?.email}`,
details: `${user.User?.email || 'email'} `,
},
{
icon: <FaPhone className="text-green-500" />,
details: `${user.User?.phone}`,
details: `${user.User?.phone || 'Contact Number'}`,
},
];

Expand Down
5 changes: 4 additions & 1 deletion src/components/profile/ProfileHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,8 +92,11 @@ function ProfileHeader() {
<div className="flex flex-col sm:flex-row items-center px-4 sm:px-10 py-5">
<img
className="w-24 h-24 sm:w-32 sm:h-32 rounded-full border-4 border-white object-cover -mt-12 sm:-mt-16 md:-mt-20"
src={user.User?.profileImage}
src={user.User?.profileImage }
alt="Profile"
onError={(e) => {
e.currentTarget.src = '/unknown.jpg';
}}
/>

<div className="flex-grow mt-4 sm:mt-0 sm:ml-4 text-center sm:text-left">
Expand Down
10 changes: 9 additions & 1 deletion src/validations/userProfileSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ birthDate: z.string().optional(),
.max(70, "No more than 70 characters for preferredLanguage"),
whereYouLive: z
.string({ required_error: "Where you live is required" })
.min(3, "Use at least 3 characters for whereYouLive")
.max(70, "No more than 70 characters for whereYouLive"),
address: z
.string({ required_error: "Address is required" })
.max(70, "No more than 70 characters for Adress"),
preferredCurrency: z
.string({ required_error: "Preferred Currency is required" })
.min(2, "Use at least 2 characters for preferredCurrency")
Expand All @@ -41,3 +43,9 @@ birthDate: z.string().optional(),
});

export default updateSchema;






0 comments on commit de094fa

Please sign in to comment.