0% found this document useful (0 votes)
0 views6 pages

Client Form to Do

The document outlines a React component named ClientForm that utilizes hooks for form handling and user authentication. It integrates form validation using Zod and provides user feedback through toast notifications. The form captures user details and handles user registration and login, redirecting to a new appointment page upon successful login.

Uploaded by

vedbhor25
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)
0 views6 pages

Client Form to Do

The document outlines a React component named ClientForm that utilizes hooks for form handling and user authentication. It integrates form validation using Zod and provides user feedback through toast notifications. The form captures user details and handles user registration and login, redirecting to a new appointment page upon successful login.

Uploaded by

vedbhor25
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/ 6

// 'use client';

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


// import { useRouter } from 'next/navigation';
// import { useContext, useEffect, useState } from 'react';
// import { useForm } from 'react-hook-form';
// import { z } from 'zod';

// import { Form } from '@/components/ui/form';


// import { UserFormValidation } from '@/lib/validation';

// import 'react-phone-number-input/style.css';
// import CustomFormField, { FormFieldType } from '../CustomFormField';
// import SubmitButton from '../SubmitButton';
// import { toast, Toaster } from 'sonner';
// import {
// createUser,
// registerUserDocument,
// } from '../../lib/actions/client.actions';
// import { UserContext } from '@/context/UserContext';

// export const ClientForm = () => {


// const userContext = useContext(UserContext);

// // Handle the case when `userContext` is undefined


// if (!userContext) {
// throw new Error('ClientForm must be used within a UserContextProvider');
// }

// const { isLoggedIn, setIsLoggedIn } = userContext;


// const router = useRouter();
// const [isLoading, setIsLoading] = useState(false);

// useEffect(() => {
// if (isLoggedIn) {
// toast.warning('Hmm Looks like you are already logged in 🤔');
// }
// }, [isLoggedIn]);

// const form = useForm<z.infer<typeof UserFormValidation>>({


// resolver: zodResolver(UserFormValidation),
// defaultValues: {
// name: '',
// email: '',
// phone: '',
// password: '',
// },
// });

// const onSubmit = async (values: z.infer<typeof UserFormValidation>) => {


// setIsLoading(true);

// try {
// const user = {
// name: values.name,
// email: values.email,
// phone: values.phone,
// password: values.password,
// };
// // Create user and handle response
// const newUser = await createUser(user);

// const response = await fetch('/api/signin', {


// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ email: user.email, password: user.password }),
// });
// console.log('response', response);

// const data = await response.json();


// console.log('data', data);

// if (data && data.status === 'success') {


// const fetchData = async () => {
// const result = await fetch('/api/user'); // Replace with your API
endpoint
// const userData = await result.json();

// if (userData && userData.status === 'success') {


// const id = userData?.user?.$id;

// const newUserDoc = {
// userId: id,
// name: values.name,
// email: values.email,
// phone: values.phone,
// password: values.password,
// };
// console.log('newUserDoc', newUserDoc);
// // registers user document in database and handles response
// await registerUserDocument(newUserDoc);
// toast.success('Login Successful! 🎉');
// router.push(`/clients/${id}/new-appointment`);
// console.log('im here 123 newUserDoc', newUserDoc);

// setIsLoggedIn(true);
// } else {
// toast.error('User data fetch failed.');
// }
// };
// } else {
// console.log('Error during user registration blabla:', data);
// toast.error(`Login Failed: ${data?.error}.`);
// }
// } catch (error) {
// console.error('Error during user registration or login:', error);
// toast.error('An error occurred. Please try again.');
// } finally {
// setIsLoading(false);
// }
// };

// return (
// <Form {...form}>
// <form onSubmit={form.handleSubmit(onSubmit)} className='flex-1 space-y-6'>
// <section className='mb-12 space-y-4'>
// <h1 className='header'>Hi there 👋</h1>
// <p className='text-dark-700'>Get started with appointments.</p>
// </section>

// <CustomFormField
// fieldType={FormFieldType.INPUT}
// control={form.control}
// name='name'
// label='Full name'
// placeholder='Enter your Name'
// iconSrc='/assets/icons/user.svg'
// iconAlt='user'
// />

// <CustomFormField
// fieldType={FormFieldType.INPUT}
// control={form.control}
// name='email'
// label='Email'
// placeholder='Enter your Email'
// iconSrc='/assets/icons/email.svg'
// iconAlt='email'
// />

// <CustomFormField
// fieldType={FormFieldType.INPUT}
// control={form.control}
// name='password'
// label='Password'
// placeholder='Enter your Password'
// iconSrc='/assets/icons/password.svg'
// iconAlt='password'
// />

// <CustomFormField
// fieldType={FormFieldType.PHONE_INPUT}
// control={form.control}
// name='phone'
// label='Phone number'
// placeholder='Enter your Phone number'
// />

// <SubmitButton isLoading={isLoading}>Get Started</SubmitButton>


// </form>
// <Toaster />
// </Form>
// );
// };

'use client';

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


import { useRouter } from 'next/navigation';
import { useContext, useEffect, useState } from 'react';
import { useForm } from 'react-hook-form';
import { z } from 'zod';

import { Form } from '@/components/ui/form';


import { UserFormValidation } from '@/lib/validation';

import 'react-phone-number-input/style.css';
import CustomFormField, { FormFieldType } from '../CustomFormField';
import SubmitButton from '../SubmitButton';
import { toast, Toaster } from 'sonner';
import {
createUser,
registerUserDocument,
} from '../../lib/actions/client.actions';
import { UserContext } from '@/context/UserContext';

export const ClientForm = () => {


const userContext = useContext(UserContext);

if (!userContext) {
throw new Error('ClientForm must be used within a UserContextProvider');
}

const { isLoggedIn, setIsLoggedIn } = userContext;


const router = useRouter();
const [isLoading, setIsLoading] = useState(false);

useEffect(() => {
if (isLoggedIn) {
toast.warning('Hmm Looks like you are already logged in 🤔');
router.push('/'); // Redirect the user if already logged in
}
}, [isLoggedIn, router]);

const form = useForm<z.infer<typeof UserFormValidation>>({


resolver: zodResolver(UserFormValidation),
defaultValues: {
name: '',
email: '',
phone: '',
password: '',
},
});

const onSubmit = async (values: z.infer<typeof UserFormValidation>) => {


setIsLoading(true);

try {
// Create the user
await createUser({
name: values.name,
email: values.email,
phone: values.phone,
password: values.password,
});

// Log the user in


const response = await fetch('/api/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: values.email,
password: values.password,
}),
});

const data = await response.json();


console.log('data', data);

if (data.status === 'success') {


const result = await fetch('/api/user');
const userData = await result.json();
console.log('userData', userData);

if (userData && userData.status === 'success') {


const id = userData?.user?.$id;

const newUserDoc = {
userId: id,
name: values.name,
email: values.email,
phone: values.phone,
password: values.password,
};

await registerUserDocument(newUserDoc);
toast.success('Login Successful! 🎉');
setIsLoggedIn(true);
router.push(`/clients/${id}/new-appointment`);
} else {
toast.error('User data fetch failed.');
}
} else {
toast.error(`Login Failed: ${data?.error}.`);
}
} catch (error) {
console.error('Error during user registration or login:', error);
toast.error('An error occurred. Please try again.');
} finally {
setIsLoading(false);
}
};

return (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className='flex-1 space-y-6'>
<section className='mb-12 space-y-4'>
<h1 className='header'>Hi there 👋</h1>
<p className='text-dark-700'>Get started with appointments.</p>
</section>

<CustomFormField
fieldType={FormFieldType.INPUT}
control={form.control}
name='name'
label='Full name'
placeholder='Enter your Name'
iconSrc='/assets/icons/user.svg'
iconAlt='user'
/>
<CustomFormField
fieldType={FormFieldType.INPUT}
control={form.control}
name='email'
label='Email'
placeholder='Enter your Email'
iconSrc='/assets/icons/email.svg'
iconAlt='email'
/>

<CustomFormField
fieldType={FormFieldType.INPUT}
control={form.control}
name='password'
label='Password'
placeholder='Enter your Password'
iconSrc='/assets/icons/password.svg'
iconAlt='password'
/>

<CustomFormField
fieldType={FormFieldType.PHONE_INPUT}
control={form.control}
name='phone'
label='Phone number'
placeholder='Enter your Phone number'
/>

<SubmitButton isLoading={isLoading}>Get Started</SubmitButton>


</form>
<Toaster />
</Form>
);
};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy