Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
158 lines (146 loc) · 4.02 KB
/
Copy pathindex.js
File metadata and controls
158 lines (146 loc) · 4.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import { useEffect, useRef, useState } from 'react' // alias to 'preact/compat'
import { request } from '@app-elements/use-request/request'
const id = val => val
const hasProp = Object.prototype.hasOwnProperty
const getVal = valOrEvent =>
valOrEvent != null && valOrEvent.target != null
? valOrEvent.target.value
: valOrEvent
const defaultOpts = {
method: 'post'
}
const INIT = 'INIT'
const SUBMIT = 'SUBMIT'
const SUCCESS = 'SUCCESS'
const FAILURE = 'FAILURE'
export const useForm = ({
action,
validations,
onSuccess,
onFailure,
opts = {},
initialData = {},
preProcess = id
}) => {
// State
const dataRef = useRef(initialData)
const errorsRef = useRef({})
const fieldNames = useRef([])
const [formState, setFormState] = useState(INIT)
// Functions
const clear = (clearErrors = true, newFormValues) => {
dataRef.current = Object.assign(
{},
Object.fromEntries(
// needs to be null not undefined, to reset inputs
Object.keys(dataRef.current).map(k => [k, null])
),
newFormValues || initialData
)
clearErrors && (errorsRef.current = {})
setFormState(INIT)
}
const field = (fieldName, {
handlerName = 'onChange',
errorClass = 'error',
hintProp = 'title'
} = {}) => {
if (!fieldNames.current.includes(fieldName)) {
fieldNames.current = [fieldName].concat(fieldNames.current)
}
const fieldProps = {}
fieldProps.name = fieldName
fieldProps.value = dataRef.current[fieldName]
fieldProps[handlerName] = (ev) => {
const value = getVal(ev)
if (formState === FAILURE) {
setFormState(INIT)
errorsRef.current = (errorsRef.current || {})[fieldName]
}
if (dataRef.current[fieldName] !== value) {
const valueObj = {}
valueObj[fieldName] = value
Object.assign(dataRef.current, valueObj)
}
}
if (hasProp.call(errorsRef.current || {}, fieldName)) {
const fieldErr = errorsRef.current[fieldName]
fieldProps[hintProp] = Array.isArray(fieldErr) ? fieldErr.join(' ') : fieldErr
fieldProps.className = errorClass
}
return fieldProps
}
const validate = (selectFields) => {
const fields = selectFields || fieldNames.current
const errors = validations == null
? {}
: fields.reduce((errs, name) => {
if (hasProp.call(validations, name)) {
const validationResult = validations[name](dataRef.current[name], dataRef.current)
if (validationResult) {
errs[name] = validationResult
}
}
return errs
}, {})
const hasError = Object.keys(errors).length > 0
return { hasError, errors }
}
const submit = (ev) => {
if (ev != null && hasProp.call(ev, 'preventDefault')) {
ev.preventDefault()
}
setFormState(SUBMIT)
}
// State effects
const effects = {
[SUBMIT]: () => {
const { hasError, errors } = validate()
if (hasError) {
errorsRef.current = errors
setFormState(FAILURE)
} else if (action) {
const reqOpts = Object.assign(
{},
defaultOpts,
opts,
{
endpoint: action,
data: preProcess(dataRef.current)
}
)
const { xhr, promise } = request(reqOpts)
promise
.then(response => {
setFormState(SUCCESS)
onSuccess && onSuccess({ response })
})
.catch(errors => {
errorsRef.current = Object.assign({}, { xhr }, errors)
setFormState(FAILURE)
})
} else {
setFormState(SUCCESS)
}
},
[SUCCESS]: () => {
if (!action) {
onSuccess && onSuccess({ formData: dataRef.current })
}
},
[FAILURE]: () => {
onFailure && onFailure(errorsRef.current)
}
}
useEffect(() => {
effects[formState] && effects[formState]()
}, [effects, formState])
return {
field,
validate,
submit,
clear,
formData: dataRef.current,
isSubmitting: formState === SUBMIT
}
}