All files / src/components/pages/auth/login/login-form index.tsx

0% Statements 0/66
0% Branches 0/1
0% Functions 0/1
0% Lines 0/66

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67                                                                                                                                     
'use client';

import { useEffect } from 'react';

import { useForm, useStore } from '@tanstack/react-form';

import { EmailField, PasswordField } from '@/components/pages/auth/fields';
import { useLogin } from '@/hooks/use-auth';
import { loginSchema } from '@/lib/schema/auth';

import { AuthSubmitButton } from '../../auth-button';

export const LoginForm = () => {
  const { handleLogin, loginError, clearLoginError } = useLogin();

  const form = useForm({
    defaultValues: {
      email: '',
      password: '',
    },
    validators: {
      onSubmit: loginSchema,
      onChange: loginSchema,
    },
    onSubmit: async ({ value, formApi }) => {
      const payload = {
        email: value.email,
        password: value.password,
      };

      await handleLogin(payload, formApi);
    },
  });

  const { email, password } = useStore(form.baseStore, (state) => state.values);

  useEffect(() => {
    clearLoginError();
  }, [email, password, clearLoginError]);

  return (
    <form
      className='flex-col-center w-full gap-8'
      onSubmit={(e) => {
        e.preventDefault();
        void form.handleSubmit();
      }}
    >
      <div className='flex-col-center w-full gap-4'>
        <form.Field children={(field) => <EmailField field={field} />} name='email' />
        <form.Field
          children={(field) => <PasswordField field={field} passwordType='loginPassword' />}
          name='password'
        />
      </div>

      <div className='flex-col-center w-full gap-2'>
        <form.Subscribe
          children={(state) => <AuthSubmitButton state={state} type='login' />}
          selector={(state) => state}
        />
        {loginError && <p className='text-error-500 text-text-sm-medium'>{loginError}</p>}
      </div>
    </form>
  );
};