forked from syhner/next-kickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
page.tsx
85 lines (78 loc) · 2.07 KB
/
page.tsx
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
'use client';
import { useState } from 'react';
import { zodResolver } from '@hookform/resolvers/zod';
import { useForm } from 'react-hook-form';
import { z } from 'zod';
import { Button } from '~/components/ui/button';
import {
Form,
FormControl,
FormDescription,
FormField,
FormItem,
FormLabel,
FormMessage,
} from '~/components/ui/form';
import { Input } from '~/components/ui/input';
import { useEvent } from '~/hooks/useEvent';
import { trpcReact } from '~/trpc/trpc-react';
const formSchema = z.object({
message: z
.string()
.min(2, {
message: 'Message must be at least 2 characters',
})
.max(50, {
message: 'Message must be not exceed 50 characters',
}),
});
export default function Page() {
const [messages, setMessages] = useState<string[]>([]);
const addMessage = trpcReact.message.useMutation();
useEvent({
channelName: 'websockets',
eventName: 'message',
onEvent: (event) => {
setMessages([event.message].concat(messages));
},
});
const form = useForm<z.infer<typeof formSchema>>({
resolver: zodResolver(formSchema),
defaultValues: {
message: '',
},
});
const onSubmit = (values: z.infer<typeof formSchema>) => {
addMessage.mutate({ message: values.message });
};
return (
<div className='mx-24 mt-12'>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className='inline'>
<FormField
control={form.control}
name='message'
render={({ field }) => (
<FormItem>
<FormControl>
<Input
className='max-w-sm'
placeholder='Your message...'
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type='submit'>Send</Button>
</form>
</Form>
<div className='mt-6'>
{messages.map((message, idx) => (
<p key={idx}>{message}</p>
))}
</div>
</div>
);
}