@whynotsnow/hooks
v0.4.0
Published
A TypeScript hooks collection for React applications.
Maintainers
Readme
@whynotsnow/hooks
React hooks for reusable application behavior.
Exports
import { useFormChainEffect } from "@whynotsnow/hooks";
import { useFormChainEffect } from "@whynotsnow/hooks/form-chain-effect";form-chain-effect
useFormChainEffect connects a form change handler to a dependency map so a changed field can trigger effects for its dependent fields. The hook only requires a FormLike object with getFieldValue(field) and getFieldsValue(), so Ant Design Form instances are compatible without making antd a package dependency.
Strict typed business form
import { defineFormChainEffectConfig } from "@whynotsnow/hooks/form-chain-effect";
type FormValues = {
A: string;
B: string;
};
type EffectResult = {
value: unknown;
};
const config = defineFormChainEffectConfig<FormValues, EffectResult>({
A: {
dependents: ["B"],
effect: (value) => ({ value }),
},
});Dynamic runtime form
import {
type AnyFormValues,
type LooseFormLike,
createFormChainEffectMap,
defineLooseFormChainEffectConfig,
setFormChainEffect,
useFormChainEffect,
} from "@whynotsnow/hooks/form-chain-effect";
const effectMap = createFormChainEffectMap<AnyFormValues>();
setFormChainEffect(effectMap, field.id, {
dependents: field.dependents,
effect: (value, allValues) => {
console.log(field.id, value, allValues);
},
});
const form: LooseFormLike = {
getFieldValue: (field) => runtimeForm.get(field),
getFieldsValue: () => runtimeForm.getAll(),
};
const { onValuesChange, manualTrigger } = useFormChainEffect({
form,
config: defineLooseFormChainEffectConfig(effectMap),
});const { onValuesChange, manualTrigger } = useFormChainEffect({
form,
config: {
A: {
dependents: ["B"],
effect: (value, allValues, chain, actions) => {
actions?.track?.("A_CHANGED", { value, path: chain.path });
},
},
B: {
effect: (value) => ({ value }),
},
},
options: {
enableAdvancedControl: true,
effectActions: {
track: console.log,
},
},
onEffectResult: ({ fieldName, result }) => {
console.log(fieldName, result);
},
});