1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-10-18 20:09:08 +02:00
unleash.unleash/frontend/src/hooks/useFormErrors.ts
olav 59c8822cf2 fix: validate feature strategy parameters (#1192)
* refactor: extract InputCaption component

* refactor: split up GeneralStrategy component

* refactor: fill inn more default feature strategy parameter values

* fix: validate feature strategy parameters

* refactor: fix duplicate keys in strategy icon list

* refactor: expand variable names

* refactor: remove unnecessary useMemo

* refactor: use captions instead of tooltips for boolean parameter descriptions

* refactor: improve strategy definition form spacing
2022-08-04 13:34:30 +02:00

60 lines
1.4 KiB
TypeScript

import { useState, useCallback } from 'react';
import produce from 'immer';
export interface IFormErrors {
// Get the error message for a field name, if any.
getFormError(field: string): string | undefined;
// Set an error message for a field name.
setFormError(field: string, message: string): void;
// Remove an existing error for a field name.
removeFormError(field: string): void;
// Check if there are any errors.
hasFormErrors(): boolean;
}
export const useFormErrors = (): IFormErrors => {
const [errors, setErrors] = useState<Record<string, string>>({});
const getFormError = useCallback(
(field: string): string | undefined => errors[field],
[errors]
);
const setFormError = useCallback(
(field: string, message: string): void => {
setErrors(
produce(draft => {
draft[field] = message;
})
);
},
[setErrors]
);
const removeFormError = useCallback(
(field: string): void => {
setErrors(
produce(draft => {
delete draft[field];
})
);
},
[setErrors]
);
const hasFormErrors = useCallback(
(): boolean => Object.values(errors).some(Boolean),
[errors]
);
return {
getFormError,
setFormError,
removeFormError,
hasFormErrors,
};
};