如何跟踪特定数组的输入字段变化并在React-hook-form ReactJS中的onChange时提交。

huangapple go评论73阅读模式
英文:

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

英文:

Based on the doc, you can create a watch for a specific field and use the useEffect hook to listen for any changes to that field to call api.

const watchNameOnly = watch("name")

Working demo

huangapple
  • 本文由 发表于 2023年6月9日 11:42:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定