You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

use-watch-change.ts 944B

12345678910111213141516171819202122232425262728293031
  1. import { omit } from 'lodash';
  2. import { useEffect } from 'react';
  3. import { UseFormReturn, useWatch } from 'react-hook-form';
  4. import { BeginQuery } from '../../interface';
  5. import useGraphStore from '../../store';
  6. function transferInputsArrayToObject(inputs: BeginQuery[] = []) {
  7. return inputs.reduce<Record<string, Omit<BeginQuery, 'key'>>>((pre, cur) => {
  8. pre[cur.key] = omit(cur, 'key');
  9. return pre;
  10. }, {});
  11. }
  12. export function useWatchFormChange(id?: string, form?: UseFormReturn) {
  13. let values = useWatch({ control: form?.control });
  14. const updateNodeForm = useGraphStore((state) => state.updateNodeForm);
  15. useEffect(() => {
  16. if (id && form?.formState.isDirty) {
  17. values = form?.getValues();
  18. const nextValues = {
  19. ...values,
  20. inputs: transferInputsArrayToObject(values.inputs),
  21. };
  22. updateNodeForm(id, nextValues);
  23. }
  24. }, [form?.formState.isDirty, id, updateNodeForm, values]);
  25. }