-
Notifications
You must be signed in to change notification settings - Fork 0
/
useForm.js
95 lines (84 loc) · 2.83 KB
/
useForm.js
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
import { useAlerts, useDataStore, useDataStoreItem } from './';
import { API } from './../api';
/**
* useForm() Hook
*
* Reusable structure for handling form submissions.
*
* @param {object} config
*
* @returns {object}
*/
function useForm(config = {}) {
/**
* Configuration
*
* @property {?number} id The database ID of the object this form is modifying.
* Null when form is creating a new object.
*
* @property {string} apiCommand The base path for the API upsert command, not including the ID.
* i.e. "climbs"
*
* @property {function} onSuccess The callback to run after a successful form submission.
* @property {function} onError The callback to run after a failed form submission.
* @property {function} onComplete The callback to run after a form submission.
*/
const {
id = null,
apiCommand = '',
onSuccess = () => {},
onError = () => {},
onComplete = () => {}
} = config;
const alerts = useAlerts();
const dataStore = useDataStore();
const { useData: data } = useDataStoreItem(id ? `${apiCommand}/${id}` : null);
/**
* onSubmit()
*
* Pass this directly to Formik's onSubmit prop.
* @link https://formik.org/docs/api/formik#onsubmit-values-values-formikbag-formikbag--void--promiseany
*
* @param {object} values
* @param {object} formikBag
*/
const onSubmit = (values, { setSubmitting }) => {
API.upsert(apiCommand, id, values)
.then((response) => {
// save the upserted object in the data store
if (response?.data?.id) {
dataStore.set(`${apiCommand}/${response.data.id}`, response.data);
}
setSubmitting(false);
// run the success callback
if (typeof onSuccess === 'function') {
onSuccess(response);
}
})
.catch((error) => {
// add the error message to the form alerts
alerts.add({
message: error?.response?.data?.message || error?.message || 'Unknown Error',
type: 'danger',
isDismissable: true
});
setSubmitting(false);
// run the error callback
if (typeof onError === 'function') {
onError(error);
}
})
.finally(() => {
// run the complete callback
if (typeof onComplete === 'function') {
onComplete();
}
});
};
return {
alerts,
data,
onSubmit
};
}
export default useForm;