How to create a custom useWatch hook to encapsulate the generic typing - Stack Overflow

I am trying to figure out how to create a custom hook that encapsulates the generic type that needs to

I am trying to figure out how to create a custom hook that encapsulates the generic type that needs to be provided to the useWatch hook. Where I am using useWatch, I am under a FormProvider, so I don't need to provide the control. With the useFormContext hook, I was able to do something like this:

import {useFormContext as useFormContextBase} from 'react-hook-form'

// create custom hook to encapsulate the generic
const useFormContext = () => useFormContextBase<FormValues>()

The useWatch hook is more verbose in terms of what you must provide it:

interface FormValues {
    username : string;
    isAdmin : boolean;
}
// having to specify the generic and values is cumbersome
const [username, isAdmin] = useWatchBase<FormValues, ['username', 'isAdmin']>({name : ['username', 'isAdmin']});

So, it would be convenient to encapsulate the first generic argument, and base the second on the value(s) passed, something like this:

// would like to do something like this, but doesn't work...
const useWatch = (name : keyof FormValues) => useWatchBase<FormValues, typeof name>({name})

This does not work properly, as the types are not properly forwarded. Does anyone know how to achieve this? Thanks in advance...

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744908798a4600421.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信