英文:
How to track changes of specific arrays of input fields and submit onChange in React-hook-form ReactJS
问题
我能使用 RHF 中的 watch() 函数来追踪所有输入更改并基于这些更改调用 API。然而,这种方法适用于所有不需要调用 API 的输入字段。所以每当用户输入任何内容时,它也会调用 API,无论他们输入什么字符,都会导致服务器崩溃。
以下是我的代码:
useEffect(() => {
const subscription = watch((data, { name }) => {
if (name === "includePA") {
const singleValue = getValues("includePA");
setChecked(singleValue);
{
singleValue == false
? setValue("premiumPA", 0)
: setValue("premiumPA", 10000000);
}
}
let timer;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
handleSubmit(onSubmitHandler)();
}, 500);
});
return () => subscription.unsubscribe();
}, [handleSubmit, watch]);
我尝试添加 unregister() 但它不起作用。请帮我解决这个问题。
英文:
I am able to track all input changes by using the watch() function in RHF and call API based on those changes. However, this method applies to all input fields that are not required to call API. So whenever user type in anything, it will also call the api by any character they type in which will make the server crashes.
Here is my code:
useEffect(() => {
const subscription = watch((data, { name }) => {
if (name === "includePA") {
const singleValue = getValues("includePA");
setChecked(singleValue);
{
singleValue == false
? setValue("premiumPA", 0)
: setValue("premiumPA", 10000000);
}
}
let timer;
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
handleSubmit(onSubmitHandler)();
}, 500);
});
return () => subscription.unsubscribe();
}, [handleSubmit, watch]);
I tried to add unregister() but it doesn't work. Please help me with this
答案1
得分: 0
根据文档,你可以创建一个监视特定字段的监视器,并使用useEffect钩子来监听该字段的任何更改以调用API。
const watchNameOnly = watch("name")
演示demo
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论