-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathErrorManager.js
More file actions
34 lines (31 loc) · 1.57 KB
/
ErrorManager.js
File metadata and controls
34 lines (31 loc) · 1.57 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
import _ from 'lodash';
import { useState } from 'react';
import { connect } from 'formik';
/**
* Error manager component that displays error only when it's right
*
* The component sets the global formik submitCount in it's local state for reference
* The local submit count is used to make sure the error message is not shown on it's initial load
*
* The local submitcount will be set to 1 less than the value of submitCount if the form is being
* submitted when the fields are mounted. This is done so that fields (such as tab fields) that are mounted
* for the sole purpose of showing error messages correctly, show the error message right during the first load
*
* The error message will be visible only after the first touch or first form submission so that
* form submitted with fields hidden do not show the a message when they show up when a certain condition is
* satisified, fieldset disclosed, tab opened, editable grid field added etc.
*
* @param {string} name
* @param {object} formik
* @param {function} children
*/
const ErrorManager = ({ name, formik, children }) => {
// Set submitCount on initial mount.
const { submitCount: formikSubmitCount, isSubmitting, errors, touched } = formik;
const [ submitCount ] = useState(isSubmitting ? formikSubmitCount - 1 : formikSubmitCount);
const isTouched = _.get(touched, name);
const errorMessage = _.get(errors, name);
const error = !_.isEmpty(errorMessage) && (isTouched || formikSubmitCount > submitCount) ? errorMessage : false;
return children(error);
};
export default connect(ErrorManager);