fix: disabled button on save and before any changes, handled errors

This commit is contained in:
Osama Malik 2024-01-29 23:33:00 +05:30
parent 651f984e52
commit 2fd6ddf0e0
2 changed files with 11 additions and 8 deletions

View file

@ -24,13 +24,13 @@ interface EditorProps {
type FormData = z.infer<typeof postPatchSchema>
export function Editor({ post }: EditorProps) {
const { register, handleSubmit } = useForm<FormData>({
const { register, handleSubmit, formState: {errors, isSubmitting, isDirty} } = useForm<FormData>({
resolver: zodResolver(postPatchSchema),
})
const ref = React.useRef<EditorJS>()
const router = useRouter()
const [isSaving, setIsSaving] = React.useState<boolean>(false)
const [isMounted, setIsMounted] = React.useState<boolean>(false)
const [editorContentChanged, setEditorContentChanged] = React.useState<boolean>(false);
const initializeEditor = React.useCallback(async () => {
const EditorJS = (await import("@editorjs/editorjs")).default
@ -50,6 +50,9 @@ export function Editor({ post }: EditorProps) {
onReady() {
ref.current = editor
},
onChange: () => {
setEditorContentChanged(true);
},
placeholder: "Type here to write your post...",
inlineToolbar: true,
data: body.content,
@ -84,7 +87,6 @@ export function Editor({ post }: EditorProps) {
}, [isMounted, initializeEditor])
async function onSubmit(data: FormData) {
setIsSaving(true)
const blocks = await ref.current?.save()
@ -99,8 +101,6 @@ export function Editor({ post }: EditorProps) {
}),
})
setIsSaving(false)
if (!response?.ok) {
return toast({
title: "Something went wrong.",
@ -138,8 +138,8 @@ export function Editor({ post }: EditorProps) {
{post.published ? "Published" : "Draft"}
</p>
</div>
<button type="submit" className={cn(buttonVariants())}>
{isSaving && (
<button disabled={isSubmitting || !(isDirty || editorContentChanged)} type="submit" className={cn(buttonVariants())}>
{isSubmitting && (
<Icons.spinner className="mr-2 h-4 w-4 animate-spin" />
)}
<span>Save</span>
@ -154,6 +154,9 @@ export function Editor({ post }: EditorProps) {
className="w-full resize-none appearance-none overflow-hidden bg-transparent text-5xl font-bold focus:outline-none"
{...register("title")}
/>
{errors.title && (
<p className="text-red-500">{`${errors.title.message}`}</p>
)}
<div id="editor" className="min-h-[500px]" />
<p className="text-sm text-gray-500">
Use{" "}

View file

@ -1,7 +1,7 @@
import * as z from "zod"
export const postPatchSchema = z.object({
title: z.string().min(3).max(128).optional(),
title: z.string().min(3, "Title must be at least 3 characters long").max(128).optional(),
// TODO: Type this properly from editorjs block types?
content: z.any().optional(),