1
1
import { NavigateFunction } from "react-router"
2
2
import { assign , createMachine } from "xstate"
3
3
import * as API from "../../api"
4
+ import { ApiError , FieldErrors , isApiError , mapApiErrorToFieldErrors } from "../../api/errors"
4
5
import * as Types from "../../api/types"
5
6
import * as TypesGen from "../../api/typesGenerated"
6
7
import { displaySuccess } from "../../components/GlobalSnackbar/utils"
@@ -14,6 +15,7 @@ export interface UsersContext {
14
15
pager ?: Types . Pager
15
16
getUsersError ?: Error | unknown
16
17
createUserError ?: Error | unknown
18
+ createUserFormErrors ?: FieldErrors
17
19
navigate ?: NavigateFunction
18
20
}
19
21
@@ -73,10 +75,17 @@ export const usersMachine = createMachine(
73
75
target : "idle" ,
74
76
actions : [ "displayCreateUserSuccess" , "redirectToUsersPage" , "clearCreateUserError" ] ,
75
77
} ,
76
- onError : {
77
- target : "idle" ,
78
- actions : [ "assignCreateUserError" ] ,
79
- } ,
78
+ onError : [
79
+ {
80
+ target : "idle" ,
81
+ cond : "isFormError" ,
82
+ actions : [ "assignCreateUserFormErrors" ] ,
83
+ } ,
84
+ {
85
+ target : "idle" ,
86
+ actions : [ "assignCreateUserError" ] ,
87
+ } ,
88
+ ] ,
80
89
} ,
81
90
tags : "loading" ,
82
91
} ,
@@ -92,6 +101,9 @@ export const usersMachine = createMachine(
92
101
getUsers : API . getUsers ,
93
102
createUser : ( _ , event ) => API . createUser ( event . user ) ,
94
103
} ,
104
+ guards : {
105
+ isFormError : ( _ , event ) => isApiError ( event . data )
106
+ } ,
95
107
actions : {
96
108
assignUsers : assign ( {
97
109
users : ( _ , event ) => event . data . page ,
@@ -107,6 +119,10 @@ export const usersMachine = createMachine(
107
119
assignCreateUserError : assign ( {
108
120
createUserError : ( _ , event ) => event . data ,
109
121
} ) ,
122
+ assignCreateUserFormErrors : assign ( {
123
+ // the guard ensures it is ApiError
124
+ createUserFormErrors : ( _ , event ) => mapApiErrorToFieldErrors ( ( event . data as ApiError ) . response . data )
125
+ } ) ,
110
126
clearCreateUserError : assign ( ( context : UsersContext ) => ( {
111
127
...context ,
112
128
createUserError : undefined ,
@@ -116,7 +132,7 @@ export const usersMachine = createMachine(
116
132
} ,
117
133
redirectToUsersPage : ( context ) => {
118
134
context . navigate && context . navigate ( "/users" )
119
- }
135
+ } ,
120
136
} ,
121
137
} ,
122
138
)
0 commit comments