All files / src/utils FormUtils.tsx

58.33% Statements 14/24
16.66% Branches 1/6
37.5% Functions 3/8
60.86% Lines 14/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                      66x 44x   44x 6x     44x     66x 1x 1x 1x 1x       1x     66x       66x         66x            
import { Form, FormInstance } from "antd";
import { GetColumnValueCallback, SaveRecordProps } from "@props/RecordProps";
import { GetColumnValueKey, OnSaveCallbackKey } from "@utils/Constants";
import { v4 as uuid } from "uuid";
import { useEffect } from "react";
 
export type OnSavedCallback = (res: {
  data?: SaveRecordProps;
  status: "fail" | "success";
}) => void;
 
export const useCustomHookForm = (): FormInstance => {
  const [form] = Form.useForm();
 
  useEffect(() => {
    form.setFieldValue(GetColumnValueKey, {});
  }, [form]);
 
  return form;
};
 
export const getFormFieldsValue = (form: FormInstance): Record<string, unknown> => {
  const values = form.getFieldsValue(true);
  const getColumnValueRecord: Record<string, GetColumnValueCallback> = form.getFieldValue(GetColumnValueKey);
  Eif (getColumnValueRecord) {
    Object.keys(getColumnValueRecord).forEach((key) => {
      values[key] = getColumnValueRecord[key]();
    });
  }
  return values;
};
 
export const getCustomValueCallback = (form: FormInstance): Record<string, GetColumnValueCallback> => {
  return form.getFieldValue(GetColumnValueKey);
};
 
export const getAllOnSavedCallback = (form: FormInstance): OnSavedCallback[] => {
  const callbackRecords: Record<string, OnSavedCallback> = form.getFieldValue(OnSaveCallbackKey) ?? {};
  return Object.values(callbackRecords);
};
 
export const registerOnSavedCallback = (form: FormInstance, callback: OnSavedCallback): () => void => {
  const callbackRecords: Record<string, OnSavedCallback> = form.getFieldValue(OnSaveCallbackKey) ?? {};
  form.setFieldValue(OnSaveCallbackKey, callbackRecords);
  const key = uuid();
  callbackRecords[key] = callback;
  return () => delete callbackRecords[key];
};