Next.js Discord

Discord Forum

Implementing use Debounce to form.

Answered
Yellow croaker posted this in #help-forum
Open in Discord
Yellow croakerOP
When implementing debounce to form, how i should do it? can i remove the <form onSubmit={handleSubmit(onSubmit)} if i'm triggering submits from onChange? I'm using React Hook Form

  const workExperienceForm = useForm<WorkExperienceSchemaType>({
    resolver: zodResolver(workExperienceSchema),
    values: workexperience,
  });
  const { register, handleSubmit, control } = workExperienceForm;


  const onSubmit = async (formData: WorkExperienceSchemaType) => {
    try {
      const workExperience = formData;
      await updateWorkExperience(workExperience);
    } catch (error) {
      console.log('Error', error);
    }
  };

  const debouncedAutoSave = useDebouncedCallback(
    () => {
      handleSubmit(onSubmit)();
    },
    2000,
    { maxWait: 5000 },
  );

return(
      <Form {...workExperienceForm}>
        <form onSubmit={handleSubmit(onSubmit)} className="space-y-8">
            <FormField
              control={control}
              name={`company`}
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Työnantaja</FormLabel>
                  <FormControl>
                    <Input
                      {...field}
                      value={field.value || ''}
                      onChange={(e) => {
                        field.onChange(e);
                        debouncedAutoSave();
                      }}
                    />
                  </FormControl>
                </FormItem>
              )}
            />
        </form>
      </Form>
)
Answered by B33fb0n3
useEffect will be called whenever the inputValue will be changed. So add more than one inputValue (more variables) and it will be called more than once
View full answer

7 Replies

What do you want to debounce? If you submit it once, the function will only be executed once. So there is no use case for debounce
Yellow croakerOP
I want to Make a submit after user writes to input. There are multiple inputs, company, position etc.
Are the input inputs controlled?
Yellow croakerOP
Yes, i use shadcn Form, and formField makes The input controlled
the you can listen for the values and debounce them like this:
React.useEffect(() => {
  const delayInputTimeoutId = setTimeout(() => {
    *function*
  }, 500);
  return () => clearTimeout(delayInputTimeoutId);
}, [inputValue, 500]);

Execute your function at *function*
Yellow croakerOP
Does it matter If i Have multiple inputs? Or how i Make use of The inputValue? Do i give it as what for The input?
useEffect will be called whenever the inputValue will be changed. So add more than one inputValue (more variables) and it will be called more than once
Answer