Passed
Push — feature/timeline-myfit-step ( 6743fb...bcf1cd )
by Yonathan
05:40
created

resources/assets/js/helpers/forms.ts   A

Complexity

Total Complexity 5
Complexity/F 0

Size

Lines of Code 53
Function Count 0

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
wmc 5
eloc 38
mnd 5
bc 5
fnc 0
dl 0
loc 53
rs 10
bpm 0
cpm 0
noi 0
c 0
b 0
f 0
1
import { FormikProps, FormikValues } from "formik";
2
import _ from "lodash";
3
import { MutableRefObject } from "react";
4
5
export const focusOnElement = (id: string): void => {
6
  const element = document.getElementById(id);
7
  if (element) {
8
    element.focus();
9
  }
10
};
11
12
export const validateAllForms = async (
13
  refs: MutableRefObject<MutableRefObject<FormikProps<FormikValues>>[]>,
14
  formBaseId: string,
15
): Promise<boolean> => {
16
  for (let i = 0; i < refs.current.length; i += 1) {
17
    let ref = refs.current[i].current;
18
    // eslint-disable-next-line no-await-in-loop
19
    const isFormValid = await refs.current[i].current
20
      .validateForm()
21
      .then(() => {
22
        ref = refs.current[i].current;
23
        if (!_.isEmpty(ref.errors) && !ref.isSubmitting && !ref.isValid) {
24
          return false;
25
        }
26
        return true;
27
      });
28
    if (!isFormValid) {
29
      focusOnElement(`${formBaseId}${ref.values.id}`);
30
      break;
31
    }
32
  }
33
34
  const invalidForm = refs.current.some(
35
    (ref: MutableRefObject<FormikProps<FormikValues>>) => !ref.current.isValid,
36
  );
37
38
  return invalidForm ? Promise.resolve(false) : Promise.resolve(true);
39
};
40
41
export const submitAllForms = async (
42
  refs: React.MutableRefObject<
43
    React.MutableRefObject<FormikProps<FormikValues>>[]
44
  >,
45
): Promise<void[]> => {
46
  return Promise.all(
47
    refs.current.map((ref: MutableRefObject<FormikProps<FormikValues>>) =>
48
      // TODO: Might need make one mass submission by combining all values into an array.
49
      ref.current.submitForm(),
50
    ),
51
  );
52
};
53