'How to pass/type react-hook-form `setValue` to custom react hook (typescript)?

How can i pass setValue to a react hook?

I have a custom react hook, where I would like to set values in a form, by passing react-hook-form's setValue. However, since the migration from v6->v7 i can't for the life of me figure out the typing.

The hook looks like:

export function useUnselectOnChange(
  id: UUID,
  setValue: any // TODO: How to type this properly
  options?: Partial<UseUnselectOnChangeOptions>,
): void {
  const { current: optionsRef } = useRef<UseUnselectOnChangeOptions>({
    fallbackValue: ReorderEnum.Top,
    fieldName: 'place',
    ...options,
  });
  const previousUuid = useRef(id);

  useLayoutEffect(() => {
    if (previousUuid.current !== id) {
      setValue(optionsRef.fieldName, optionsRef.fallbackValue);
    }

    previousUuid.current = id;
  }, [id, setValue, optionsRef]);
}

Used like this:

useUnselectOnChange(id, setValue, {
  fallbackValue: '',
  fieldName: 'component',
});

Previously setValue: UseFormMethods<Record<string, string>>['setValue'] worked but UseFormMethods does not exist anymore. I use useFrom<FormValues>() to get the form methods (setValue ++). This is how I do it in every component. FormValues is the where I specify the members and types of each form (so every FormValues is different). I can't figure out a generic typing in my hook that will accept setValue. Ideas?



Solution 1:[1]

It looks like you'll need to use a generic and the UseFormSetValue type that your custom hook takes. So it'll be

function customHook<T>(setValue:UseFormSetValue<T>){
  return []
}

then used like

const [] = customHook<IFormInput>(setValue)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Leon