98 lines
2.8 KiB
TypeScript
98 lines
2.8 KiB
TypeScript
import { gql } from '@apollo/client';
|
|
import { bookListQuery } from '@app/client/components/BookSearchList';
|
|
import { useToastMutation } from '@app/client/hooks/useToastMutation';
|
|
import { Heading, Input, Stack, Textarea } from '@chakra-ui/react';
|
|
import { Button } from '@client/components/ui/button';
|
|
import { Field } from '@client/components/ui/field';
|
|
import { CreateNewBookMutation } from '@generated/types';
|
|
import { valibotResolver } from '@hookform/resolvers/valibot';
|
|
import { createFileRoute, redirect, useNavigate } from '@tanstack/react-router';
|
|
import { useForm } from 'react-hook-form';
|
|
import * as v from 'valibot';
|
|
|
|
export const Route = createFileRoute('/new/book')({
|
|
component: RouteComponent,
|
|
beforeLoad: ({ context }) => {
|
|
if (!context.isAuthenticated) throw redirect({ to: '/' });
|
|
}
|
|
});
|
|
|
|
function RouteComponent() {
|
|
return (
|
|
<Stack width="100%" flexDirection={'column'} justifyContent={'center'} alignItems={'center'}>
|
|
<Heading>New book</Heading>
|
|
<NewBookForm />
|
|
</Stack>
|
|
);
|
|
}
|
|
|
|
interface FormValues {
|
|
title: string;
|
|
description: string;
|
|
}
|
|
|
|
function NewBookForm() {
|
|
const navigate = useNavigate();
|
|
const { update: bookCreate } = useToastMutation<CreateNewBookMutation>({
|
|
mutation: bookCreateMutation,
|
|
successMsg: 'Book created successfully!',
|
|
refetchQueries: [bookListQuery]
|
|
});
|
|
|
|
const schema = v.pipe(
|
|
v.object({
|
|
title: v.pipe(v.string(), v.nonEmpty('Title is required'), v.maxLength(60)),
|
|
description: v.pipe(v.string(), v.nonEmpty('Description is required'), v.maxLength(900))
|
|
})
|
|
);
|
|
|
|
const {
|
|
register,
|
|
handleSubmit,
|
|
formState: { errors }
|
|
} = useForm<FormValues>({ resolver: valibotResolver(schema) });
|
|
|
|
return (
|
|
<form
|
|
style={{ width: '80%', maxWidth: '840px' }}
|
|
onSubmit={handleSubmit(async values => {
|
|
const { data } = await bookCreate({
|
|
variables: {
|
|
input: {
|
|
title: values.title,
|
|
description: values.description
|
|
}
|
|
}
|
|
});
|
|
if (data != null)
|
|
navigate({
|
|
to: `/work/book/${data.bookCreate.id}/overview/contents`
|
|
});
|
|
})}
|
|
>
|
|
<Stack>
|
|
<Field label="Title" invalid={errors.title != null} errorText={errors.title?.message}>
|
|
<Input {...register('title')} />
|
|
</Field>
|
|
<Field
|
|
label="Description"
|
|
invalid={errors.description != null}
|
|
errorText={errors.description?.message}
|
|
>
|
|
<Textarea width="100%" height={'sm'} {...register('description')} />
|
|
</Field>
|
|
<Button type="submit">Create new book</Button>
|
|
</Stack>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
const bookCreateMutation = gql`
|
|
mutation CreateNewBook($input: BookCreateInput!) {
|
|
bookCreate(input: $input) {
|
|
id
|
|
title
|
|
description
|
|
}
|
|
}
|
|
`;
|