Connect, collaborate, and grow with a community of TypeScript developers
react form g0d.. ong
Chris Bautistae091e6777b05
diff --git a/src/components/settings/index.tsx b/src/components/settings/index.tsxindex 65386cb5..eaacfd13 100644--- a/src/components/settings/index.tsx+++ b/src/components/settings/index.tsx@@ -1,29 +1,22 @@'use client';-import { Controller, useFieldArray, useForm } from 'react-hook-form';+import { zodResolver } from '@hookform/resolvers/zod';+import { Github, Link as LinkIcon, Linkedin, Twitter, Youtube } from 'lucide-react';+import { Controller, useFieldArray, useForm, useWatch } from 'react-hook-form';+import * as z from 'zod';import { Button } from '../ui/button';+import { Form, FormItem } from '../ui/form';import { Input } from '../ui/input';-import { updateProfile } from './settings.action';-import * as z from 'zod';-import { zodResolver } from '@hookform/resolvers/zod';import { RichMarkdownEditor } from '../ui/rich-markdown-editor';-import { Github, Linkedin, Twitter, Youtube, Link as LinkIcon } from 'lucide-react';-import { toast } from '../ui/use-toast';import { ToastAction } from '../ui/toast';-import { ErrorMessage } from '@hookform/error-message';+import { toast } from '../ui/use-toast';+import { updateProfile } from './settings.action';export interface UserLinkType {id: string | null;url: string;}-interface FormValues {- userLinks: UserLinkType[];- bio: string;-}--export type FormSchema = z.infer<typeof formSchema>;-const formSchema = z.object({userLinks: z.array(z.object({@@ -34,34 +27,34 @@ const formSchema = z.object({bio: z.string().optional(),});+export type FormSchema = z.infer<typeof formSchema>;+export const Settings = ({ profileData }: { profileData: FormSchema }) => {- const {- formState: { isValid, errors },- control,- getValues,- register,- } = useForm<FormValues>({+ const form = useForm<FormSchema>({resolver: zodResolver(formSchema),defaultValues: {...profileData,},});+ const {+ formState: { errors },+ control,+ getValues,+ register,+ } = form;++ const userLinks = useWatch({ control: form.control, name: 'userLinks' });+const { fields } = useFieldArray({control,name: 'userLinks',});- const onSubmit = async (values: FormValues) => {- if (!isValid) {- toast({- variant: 'destructive',- title: 'You must put a valid link',- action: <ToastAction altText="Error in urls">Error in url</ToastAction>,- });- return;- }+ const onSubmit = async (values: FormSchema) => {+ const isValid = await form.trigger();+ if (!isValid) return;// call the server actionawait updateProfile(values);@@ -75,49 +68,50 @@ export const Settings = ({ profileData }: { profileData: FormSchema }) => {return (<div className="container"><h2 className="mt-10 text-3xl font-bold">Profile</h2>- <form action={() => onSubmit(getValues())}>- <h4 className="mb-4 text-xl">Tell us about yourself</h4>- <div className="h-[300px] w-[600px]">- <Controller- control={control}- name="bio"- render={({ field: { onChange, value } }) => (- <RichMarkdownEditor value={value} onChange={onChange} />- )}- />- </div>-- {/* TODO: get errors working on each field */}- <ErrorMessage errors={errors} name="userLinks" render={({ message }) => <p>{message}</p>} />-- <div className="mt-8 flex flex-col items-start space-y-3">- <h4 className="text-xl font-bold">Social accounts</h4>- {fields- .map((val, i) => {+ <Form {...form}>+ <form action={() => onSubmit(getValues())}>+ <h4 className="mb-4 text-xl">Tell us about yourself</h4>+ <div className="h-[300px] w-[600px]">+ <Controller+ control={control}+ name="bio"+ render={({ field: { onChange, value } }) => (+ <RichMarkdownEditor value={value as string} onChange={onChange} />+ )}+ />+ </div>+ <div className="mt-8 flex flex-col items-start space-y-3">+ <h4 className="text-xl font-bold">Social accounts</h4>+ {fields.map((val, i) => {return (- <div key={`url-${i}`} className="flex items-center gap-2">- <MagikcIcon url={val?.url ?? ''} />- <Input- defaultValue={val?.url}- placeholder="Link to social profile"- className="w-64"- // @ts-ignore- {...register(`userLinks.${i}.url`)}- />- </div>+ <FormItem className="mb-3" key={`url-link-${i}`}>+ <div className="flex items-center gap-2">+ <MagicIcon url={userLinks?.[i]?.url ?? ''} />+ <Input+ defaultValue={val?.url}+ placeholder="Link to social profile"+ className="w-64"+ {...register(`userLinks.${i}.url`)}+ />+ {errors.userLinks?.[i]?.url?.message && (+ <div className="text-red-500">{errors.userLinks?.[i]?.url?.message}</div>+ )}+ </div>+ </FormItem>);})}- </div>+ </div>- <Button type="submit" className="mt-6">- Save- </Button>- </form>+ <Button type="submit" className="mt-6">+ Save+ </Button>+ </form>+ </Form></div>);};-function MagikcIcon({ url }: { url: string }) {+function MagicIcon({ url }: { url: string }) {if (url.startsWith('https://github.com/')) return <Github className="h-5 w-5 text-neutral-400" />;if (url.startsWith('https://twitter.com/'))return <Twitter className="h-5 w-5 text-neutral-400" />;diff --git a/src/components/settings/settings.action.ts b/src/components/settings/settings.action.tsindex 6665a23a..f9092972 100644--- a/src/components/settings/settings.action.ts+++ b/src/components/settings/settings.action.ts@@ -4,7 +4,7 @@ import { getServerSession } from 'next-auth';import { prisma } from '~/server/db';import { authOptions } from '~/server/auth';-import type { UserLinkType } from '.';+import type { FormSchema, UserLinkType } from '.';import { revalidatePath } from 'next/cache';/**@@ -12,7 +12,7 @@ import { revalidatePath } from 'next/cache';* @param profileData*/// TODO: add transactions to this update #GFI-export async function updateProfile(profileData: { bio: string; userLinks: UserLinkType[] }) {+export async function updateProfile(profileData: FormSchema) {const session = await getServerSession(authOptions);// 1. Checks that the user is logged in@@ -26,17 +26,16 @@ export async function updateProfile(profileData: { bio: string; userLinks: UserL// 3. Update the users links in the db if the url is not emptyawait prisma.$transaction(- profileData.userLinks- .map((link) =>- prisma.userLink.upsert({- where: { id: link.id ?? '' },- update: { url: link.url },- create: {- url: link.url,- user: { connect: { id: session?.user.id } },- },- }),- ),+ profileData.userLinks.map((link) =>+ prisma.userLink.upsert({+ where: { id: link.id ?? '' },+ update: { url: link.url },+ create: {+ url: link.url,+ user: { connect: { id: session?.user.id } },+ },+ }),+ ),);// do this after we do the shitdiff --git a/src/components/ui/rich-markdown-editor.tsx b/src/components/ui/rich-markdown-editor.tsxindex 9e2c6ee6..9117173e 100644--- a/src/components/ui/rich-markdown-editor.tsx+++ b/src/components/ui/rich-markdown-editor.tsx@@ -1,5 +1,5 @@import { useTheme } from 'next-themes';-import { useContext } from 'react';+import { useContext, useEffect } from 'react';import MDEditor, { commands, type ICommand, EditorContext } from '@uiw/react-md-editor';@@ -59,9 +59,11 @@ interface Props {export function RichMarkdownEditor({ value, onChange }: Props) {const { theme } = useTheme();- theme == 'dark'- ? document.documentElement.setAttribute('data-color-mode', 'dark')- : document.documentElement.setAttribute('data-color-mode', 'light');+ useEffect(() => {+ theme == 'dark'+ ? document.documentElement.setAttribute('data-color-mode', 'dark')+ : document.documentElement.setAttribute('data-color-mode', 'light');+ }, [theme]);return (<div className="h-full flex-1">