@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
54 lines (53 loc) • 2.76 kB
JavaScript
"use client";
import { useCallback, useContext, useMemo } from 'react';
import { createReferenceKey, useSharedState } from '../../../../shared/helpers/useSharedState';
import DataContext from '../../DataContext/Context';
export default function useValidation() {
let id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
const {
data
} = useSharedState(createReferenceKey(id, 'attachments'));
const fallback = useCallback(() => false, []);
const context = useContext(DataContext);
const hasErrors = (data === null || data === void 0 ? void 0 : data.hasErrors) || !id && (context === null || context === void 0 ? void 0 : context.hasErrors) || fallback;
const hasFieldError = (data === null || data === void 0 ? void 0 : data.hasFieldError) || !id && (context === null || context === void 0 ? void 0 : context.hasFieldError) || fallback;
const setSubmitState = (data === null || data === void 0 ? void 0 : data.setSubmitState) || !id && (context === null || context === void 0 ? void 0 : context.setSubmitState) || fallback;
const setFormError = useCallback(error => {
setSubmitState === null || setSubmitState === void 0 ? void 0 : setSubmitState({
error
});
}, [setSubmitState]);
const {
getFieldConnections
} = useConnections(id);
const setFieldStatus = useCallback((path, status) => {
var _connections$path, _connections$path$set;
const connections = getFieldConnections();
connections === null || connections === void 0 ? void 0 : (_connections$path = connections[path]) === null || _connections$path === void 0 ? void 0 : (_connections$path$set = _connections$path.setEventResult) === null || _connections$path$set === void 0 ? void 0 : _connections$path$set.call(_connections$path, status);
}, [getFieldConnections]);
return useMemo(() => ({
hasErrors,
hasFieldError,
setFormError,
setFieldStatus
}), [hasErrors, hasFieldError, setFormError, setFieldStatus]);
}
function useConnections() {
let id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
const {
get
} = useSharedState(createReferenceKey(id, 'attachments'));
const dataContext = useContext(DataContext);
const {
fieldConnectionsRef
} = dataContext || {};
const getFieldConnections = useCallback(() => {
const attachments = get();
const connections = (attachments === null || attachments === void 0 ? void 0 : attachments.fieldConnectionsRef) || !id && fieldConnectionsRef;
return connections === null || connections === void 0 ? void 0 : connections.current;
}, [fieldConnectionsRef, get, id]);
return useMemo(() => ({
getFieldConnections
}), [getFieldConnections]);
}
//# sourceMappingURL=useValidation.js.map