Skip to content

Commit

Permalink
Merge pull request #24 from MakerXStudio/fix/validation-messages-not-…
Browse files Browse the repository at this point in the history
…showing

Fix: a bug where validation messages would only show after an externally triggered re-render
  • Loading branch information
tristanmenzel authored May 19, 2023
2 parents 3b57c64 + 5992f34 commit c6b5752
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 4 deletions.
6 changes: 6 additions & 0 deletions .changeset/dull-spies-refuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@makerx/forms-core': patch
'@makerx/forms-mui': patch
---

Fix bug where validation errors would only show after an externally triggered re-render
9 changes: 9 additions & 0 deletions packages/core/src/hooks/useFormFieldError.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { useFormContext } from 'react-hook-form'
import type { FieldError } from 'react-hook-form/dist/types/errors'

export const useFormFieldError = (field: string): FieldError | undefined => {
const {
formState: { errors },
} = useFormContext()
return field.split('.').reduce((acc: any, cur) => acc?.[cur], errors)
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ export { z } from 'zod';
export { zfd } from 'zod-form-data';
export * from './components/ValidatedFormFactory';
export * from './hooks/useFieldMetadata';
export * from './hooks/useFormFieldError';
export * from './util/FormFieldHelperBase';
8 changes: 5 additions & 3 deletions packages/mui/src/components/form-item/FormItem.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useFieldMetaData } from '@makerx/forms-core';
import { useFieldMetaData, useFormFieldError } from '@makerx/forms-core';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import { InputLabel, Tooltip, Typography } from '@mui/material';
import clsx from 'clsx';
Expand Down Expand Up @@ -30,9 +30,11 @@ export function FormItem<
field,
longHint,
}: FormItemProps<TSchema>) {
const { getFieldState } = useFormContext();
const {
formState: { errors },
} = useFormContext();
const { required } = useFieldMetaData(field);
const { error } = getFieldState(field);
const error = useFormFieldError(field);
const errorMessage = error?.message;
return (
<div>
Expand Down
3 changes: 2 additions & 1 deletion packages/mui/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@
"isolatedModules": true,
"jsx": "react-jsx"
},
"include": ["src"]
"include": ["src"],

}

0 comments on commit c6b5752

Please sign in to comment.