errorHandling.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { FormikErrors, FormikTouched } from 'formik';
  2. import { LabelProps } from 'semantic-ui-react';
  3. type FieldErrorLabelProps = LabelProps | null; // This is used for displaying semantic-ui errors
  4. export type FormErrorLabelsProps<ValuesT> = { [T in keyof ValuesT]: FieldErrorLabelProps };
  5. // Single form field error state.
  6. // Takes formik "errors" and "touched" objects and the field name as arguments.
  7. // Returns value to use ie. in the semantic-ui Form.Input error prop.
  8. export function getErrorLabelProps<ValuesT> (
  9. errors: FormikErrors<ValuesT>,
  10. touched: FormikTouched<ValuesT>,
  11. fieldName: keyof ValuesT,
  12. pointing: LabelProps['pointing'] = undefined
  13. ): FieldErrorLabelProps {
  14. return (errors[fieldName] && touched[fieldName])
  15. ? { content: errors[fieldName], pointing }
  16. : null;
  17. }
  18. // All form fields error states (uses default value for "pointing").
  19. // Takes formik "errors" and "touched" objects as arguments.
  20. // Returns object with field names as properties and values that can be used ie. for semantic-ui Form.Input error prop
  21. export function getFormErrorLabelsProps<ValuesT> (
  22. errors: FormikErrors<ValuesT>,
  23. touched: FormikTouched<ValuesT>
  24. ): FormErrorLabelsProps<ValuesT> {
  25. const errorStates: Partial<FormErrorLabelsProps<ValuesT>> = {};
  26. for (const fieldName in errors) {
  27. errorStates[fieldName] = getErrorLabelProps<ValuesT>(errors, touched, fieldName);
  28. }
  29. return errorStates as FormErrorLabelsProps<ValuesT>;
  30. }