Skip to content

Commit

Permalink
notes/ page.tsx error at 1.28
Browse files Browse the repository at this point in the history
added shad cn react - hook - form with zod
add note dialauge added
  • Loading branch information
abhishekHegde2000 committed Nov 23, 2023
1 parent 9064f8d commit 0df2686
Showing 1 changed file with 103 additions and 0 deletions.
103 changes: 103 additions & 0 deletions src/components/AddNoteDialog.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { CreateNoteSchema, createNoteSchema } from "@/lib/validation/note";
import { zodResolver } from "@hookform/resolvers/zod";
import { useRouter } from "next/navigation";
import { useForm } from "react-hook-form";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "./ui/dialog";
import {
Form,
FormControl,
FormField,
FormItem,
FormLabel,
FormMessage,
} from "./ui/form";
import { Input } from "./ui/input";
import LoadingButton from "./ui/loading-button";
import { Textarea } from "./ui/textarea";

interface AddNoteDialogProps {
open: boolean;
setOpen: (open: boolean) => void;
}

export default function AddNoteDialog({ open, setOpen }: AddNoteDialogProps) {
const router = useRouter();

const form = useForm<CreateNoteSchema>({
resolver: zodResolver(createNoteSchema),
defaultValues: {
title: "",
content: "",
},
});

async function onSubmit(input: CreateNoteSchema) {
try {
const response = await fetch("/api/notes", {
method: "POST",
body: JSON.stringify(input),
});
if (!response.ok) throw Error("Status code: " + response.status);
form.reset();
router.refresh();
setOpen(false);
} catch (error) {
console.error(error);
alert("Something went wrong. Please try again.");
}
}

return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogContent>
<DialogHeader>
<DialogTitle>Add Note</DialogTitle>
</DialogHeader>
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-3">
<FormField
control={form.control}
name="title"
render={({ field }) => (
<FormItem>
<FormLabel>Note title</FormLabel>
<FormControl>
<Input placeholder="Note title" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormLabel>Note content</FormLabel>
<FormControl>
<Textarea placeholder="Note content" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<DialogFooter>
<LoadingButton
type="submit"
loading={form.formState.isSubmitting}
>
Submit
</LoadingButton>
</DialogFooter>
</form>
</Form>
</DialogContent>
</Dialog>
);
}

0 comments on commit 0df2686

Please sign in to comment.