1
1
import { FetcherWithComponents , useActionData } from "@remix-run/react" ;
2
- import { ValidationErrorResponseData , FORM_ID_FIELD_NAME } from "@rvf/core" ;
2
+ import {
3
+ ValidationErrorResponseData ,
4
+ FORM_ID_FIELD_NAME ,
5
+ FieldValues ,
6
+ } from "@rvf/core" ;
3
7
4
8
type ErrorResponseContext = {
5
9
fetcher ?: FetcherWithComponents < unknown > ;
@@ -21,23 +25,32 @@ function useErrorResponseForForm({
21
25
return actionData . formId === formId ? actionData : null ;
22
26
}
23
27
24
- export const useServerValidationErrors = (
25
- formIdOrFetcher : string | FetcherWithComponents < any > ,
28
+ export type ServerValidationErrorOpts < DefaultValues > = (
29
+ | { formId : string }
30
+ | { fetcher : FetcherWithComponents < unknown > }
31
+ ) & {
32
+ defaultValues : DefaultValues ;
33
+ } ;
34
+
35
+ export const useServerValidationErrors = < DefaultValues extends FieldValues > (
36
+ opts : ServerValidationErrorOpts < DefaultValues > ,
26
37
) => {
27
- const formId =
28
- typeof formIdOrFetcher === "string" ? formIdOrFetcher : undefined ;
29
- const fetcher =
30
- typeof formIdOrFetcher === "string" ? undefined : formIdOrFetcher ;
38
+ const { defaultValues } = opts ;
39
+ const formId = "formId" in opts ? opts . formId : undefined ;
40
+ const fetcher = "fetcher" in opts ? opts . fetcher : undefined ;
41
+
31
42
const errorsFromServer = useErrorResponseForForm ( {
32
43
fetcher,
33
44
formId,
34
45
} ) ;
46
+ const errorDefaultValues = errorsFromServer ?. repopulateFields ;
35
47
36
48
return {
37
49
getFormOpts : ( ) => ( {
38
50
serverValidationErrors : errorsFromServer ?. fieldErrors ,
39
51
id : formId ,
40
52
fetcher,
53
+ defaultValues : ( errorDefaultValues ?? defaultValues ) as DefaultValues ,
41
54
} ) ,
42
55
renderHiddenInput : ( ) => (
43
56
< input type = "hidden" name = { FORM_ID_FIELD_NAME } value = { formId } />
0 commit comments