From ad61cf2d937128103d217e6ff89d17e34ef06ca7 Mon Sep 17 00:00:00 2001 From: keyurparalkar Date: Tue, 16 Apr 2024 10:51:19 +0530 Subject: [PATCH] feat: added error messages of the editor in the status bar --- src/App.tsx | 29 +++++++++++++++++++++++----- src/components/fields/InputField.tsx | 1 - 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/src/App.tsx b/src/App.tsx index 0c81662..97ecadc 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from "react"; +import { useCallback, useMemo, useState } from "react"; import { useForm } from "react-hook-form"; import CodeMirror from "@uiw/react-codemirror"; import { json } from "@codemirror/lang-json"; @@ -6,6 +6,7 @@ import { json } from "@codemirror/lang-json"; import personalInfoSchema from "./schemas/forms/personal_info.json"; import { SchemaDef } from "./interfaces/schema"; import SchemaRenderer from "./components/ui/SchemaRenderer"; +import { ZodError } from "zod"; const schema = SchemaDef.parse(personalInfoSchema); @@ -20,11 +21,27 @@ export type TFormValues = typeof FormValues; function App() { const [value, setValue] = useState(schema); - const onChange = useCallback((val) => { - const tempSchema = SchemaDef.parse(JSON.parse(val)); - setValue(tempSchema); + const [editorError, setEditorError] = useState(); + + const onChange = useCallback((val: string) => { + try { + const tempSchema = SchemaDef.parse(JSON.parse(val)); + setValue(tempSchema); + setEditorError(undefined); + } catch (error) { + setEditorError(error as ZodError); + } }, []); + const errorMessage = useMemo(() => { + if (editorError && editorError.issues[0]) { + const firstIssue = editorError.issues[0]; + return firstIssue.code === "invalid_union" + ? firstIssue.unionErrors[0] + : ""; + } + }, [editorError]); + const { register, handleSubmit, @@ -61,7 +78,9 @@ function App() { -
+
+ {errorMessage && JSON.stringify(errorMessage.issues[0])} +
); } diff --git a/src/components/fields/InputField.tsx b/src/components/fields/InputField.tsx index e350ee6..2f33a63 100644 --- a/src/components/fields/InputField.tsx +++ b/src/components/fields/InputField.tsx @@ -14,7 +14,6 @@ interface InputFieldProps extends InputProps { const InputField = (props: InputFieldProps) => { const { htmlFor, register, labelText, validation, error, ...rest } = props; - console.log({ htmlFor, validation }); return ( <>