Skip to content

Commit

Permalink
fix(forms): Fix data context provider path and error state handling (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
henit authored Nov 22, 2023
1 parent 5d94842 commit 01a01f4
Show file tree
Hide file tree
Showing 6 changed files with 679 additions and 574 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export interface ContextState {
mountedFieldPaths: string[]
handleMountField: (path: string) => void
handleUnMountField: (path: string) => void
setPathWithError: (path: string, hasError: boolean) => void
setValueWithError: (identifier: string, hasError: boolean) => void
hasErrors: () => boolean
_isInsideFormElement?: boolean
}
Expand All @@ -35,7 +35,7 @@ export const defaultContextState: ContextState = {
handleMountField: () => null,
handleUnMountField: () => null,
hasErrors: () => false,
setPathWithError: () => null,
setValueWithError: () => null,
_isInsideFormElement: false,
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export default function Provider<Data extends JsonObject>({
showAllErrorsRef.current = showAllErrors
}, [])
// - Errors reported by fields, based on their direct validation rules
const pathsWithErrorRef = useRef<string[]>([])
const valuesWithErrorRef = useRef<string[]>([])
// - Data
const initialData = useMemo(() => {
if (sessionStorageId && typeof window !== 'undefined') {
Expand Down Expand Up @@ -133,17 +133,21 @@ export default function Provider<Data extends JsonObject>({
mountedFieldPathsRef.current.find(
(mountedFieldPath) =>
errorsRef.current?.[mountedFieldPath] !== undefined ||
pathsWithErrorRef.current.includes(mountedFieldPath)
valuesWithErrorRef.current.includes(mountedFieldPath)
)
),
[]
)

const setPathWithError = useCallback(
(path: string, hasError: boolean) => {
pathsWithErrorRef.current = hasError
? addListPath(pathsWithErrorRef.current, path)
: removeListPath(pathsWithErrorRef.current, path)
const setValueWithError = useCallback(
(identifier: string, withError: boolean) => {
if (withError !== valuesWithErrorRef.current.includes(identifier)) {
// The boolean error state for the target value was changed
valuesWithErrorRef.current = withError
? addListPath(valuesWithErrorRef.current, identifier)
: removeListPath(valuesWithErrorRef.current, identifier)
forceUpdate()
}
},
[]
)
Expand Down Expand Up @@ -223,6 +227,7 @@ export default function Provider<Data extends JsonObject>({
} else {
showAllErrorsRef.current = true
onSubmitRequest?.()
forceUpdate()
}
return internalDataRef.current
},
Expand Down Expand Up @@ -261,7 +266,7 @@ export default function Provider<Data extends JsonObject>({
handleMountField,
handleUnMountField,
hasErrors,
setPathWithError,
setValueWithError,
}}
>
{children}
Expand Down
Loading

0 comments on commit 01a01f4

Please sign in to comment.