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 ( <>