89 lines
2.2 KiB
TypeScript
89 lines
2.2 KiB
TypeScript
import { gql } from '@apollo/client';
|
|
import { Heading, Input, Stack } from '@chakra-ui/react';
|
|
import { Button } from '@client/components/ui/button';
|
|
import { Field } from '@client/components/ui/field';
|
|
import { valibotResolver } from '@hookform/resolvers/valibot';
|
|
import { createFileRoute } from '@tanstack/react-router';
|
|
import { Session } from 'inspector';
|
|
import { useForm } from 'react-hook-form';
|
|
import * as v from 'valibot';
|
|
import { sessionFragment } from '../fragments';
|
|
import { useToastMutation } from '../hooks/useToastMutation';
|
|
|
|
export const Route = createFileRoute('/login')({
|
|
component: LoginComponent
|
|
});
|
|
|
|
function LoginComponent() {
|
|
return (
|
|
<Stack flexDirection={'column'} justifyContent={'center'} alignItems={'center'}>
|
|
<Heading>Login</Heading>
|
|
<LoginForm />
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
interface FormValues {
|
|
email: string;
|
|
password: string;
|
|
}
|
|
|
|
function LoginForm() {
|
|
const { update: login } = useToastMutation<Session>({
|
|
mutation,
|
|
successMsg: 'Logged in successfully.'
|
|
});
|
|
|
|
const schema = v.pipe(
|
|
v.object({
|
|
email: v.pipe(v.string(), v.nonEmpty('Email is required'), v.email('Invalid email')),
|
|
password: v.pipe(v.string(), v.nonEmpty('Password is required'))
|
|
})
|
|
);
|
|
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
formState: { errors }
|
|
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
|
|
|
return (
|
|
<form
|
|
onSubmit={handleSubmit(async values => {
|
|
const { data } = await login({
|
|
variables: {
|
|
input: {
|
|
email: values.email,
|
|
password: values.password
|
|
}
|
|
}
|
|
});
|
|
alert(JSON.stringify(data));
|
|
})}
|
|
>
|
|
<Stack>
|
|
<Field label="Email" invalid={errors.email != null} errorText={errors.email?.message}>
|
|
<Input {...register('email')} />
|
|
</Field>
|
|
<Field
|
|
label="Password"
|
|
invalid={errors.password != null}
|
|
errorText={errors.password?.message}
|
|
>
|
|
<Input {...register('password')} />
|
|
</Field>
|
|
<Button type="submit">Sign in</Button>
|
|
</Stack>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
const mutation = gql`
|
|
mutation AuthLogin($input: LoginInput!) {
|
|
login(input: $input) {
|
|
...Session
|
|
}
|
|
}
|
|
|
|
${sessionFragment}
|
|
`;
|