@mantine/form
Version:
Mantine form management library
52 lines (51 loc) • 2.08 kB
JavaScript
"use client";
import { getPath } from "../../paths/get-path.mjs";
import { useCallback, useEffect, useRef } from "react";
//#region packages/@mantine/form/src/hooks/use-form-watch/use-form-watch.ts
function useFormWatch({ $values, $status, cascadeUpdates }) {
const subscribers = useRef({});
return {
subscribers,
watch: useCallback((path, callback) => {
useEffect(() => {
subscribers.current[path] = subscribers.current[path] || [];
subscribers.current[path].push(callback);
return () => {
subscribers.current[path] = subscribers.current[path].filter((cb) => cb !== callback);
};
}, [callback]);
}, []),
getFieldSubscribers: useCallback((path) => {
const result = subscribers.current[path]?.map((callback) => (input) => callback({
previousValue: getPath(path, input.previousValues),
value: getPath(path, input.updatedValues),
touched: $status.isTouched(path),
dirty: $status.isDirty(path)
})) ?? [];
for (const subscriptionKey in subscribers.current) {
const isParent = String(path).startsWith(`${subscriptionKey}.`);
const isChild = String(subscriptionKey).startsWith(`${path}.`);
if (isParent || cascadeUpdates && isChild) result.push(...subscribers.current[subscriptionKey].map((cb) => (input) => cb({
previousValue: getPath(subscriptionKey, input.previousValues),
value: getPath(subscriptionKey, input.updatedValues),
touched: $status.isTouched(subscriptionKey),
dirty: $status.isDirty(subscriptionKey)
})));
}
return result;
}, []),
notifyWatchSubscribers: useCallback((previousValues) => {
Object.keys(subscribers.current).forEach((path) => {
if (getPath(path, $values.refValues.current) !== getPath(path, previousValues)) subscribers.current[path]?.forEach((cb) => cb({
previousValue: getPath(path, previousValues),
value: getPath(path, $values.refValues.current),
touched: $status.isTouched(path),
dirty: $status.isDirty(path)
}));
});
}, [])
};
}
//#endregion
export { useFormWatch };
//# sourceMappingURL=use-form-watch.mjs.map