0

I am working a nextjs project.

I use useform reactjs.

I tried to save one of a watchfield in a state

I got this error in terminal.

state areaCodeundefined undefined watchAllFields undefined undefined

error - Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

I tried with this codes


  const {
    handleSubmit,
    control,
    register,
    watch,
    getValues,
    reset,
    formState: { isSubmitting },
  } = useForm<IPassengerForm>({
    defaultValues: {
      adultPassenger: [],
      childPassenger: [],
      infantPassenger: [],
    },
    resolver: yupResolver(passengerSchema),
    mode: 'all',
  });

  const watchAllFields = watch();
  console.log('watchAllFields', watchAllFields.adultPassenger[0]?.areaCode);
  const getAreaCode = getValues(`adultPassenger.0.areaCode`);
  console.log(getAreaCode);
  if (watchAllFields.adultPassenger) {
    setareaCode(String(watchAllFields.adultPassenger[0]?.areaCode));
  }

  <Controller
                                control={control}
                                // @ts-ignore
                                name={`adultPassenger.${number}.areaCode`}
                                render={({
                                  field,
                                  fieldState: { error, invalid },
                                }) => (
                                  <TextField
                                    fullWidth
                                    helperText={error?.message}
                                    error={invalid}
                                    id="outlined-basic"
                                    label="Area Code"
                                    variant="outlined"
                                    {...field}
                                    {...register(
                                      `adultPassenger.${number}.areaCode`
                                    )}
                                  />
                                )}
                              />

Why this error occur? Anyone explain me?

hanushic
  • 369
  • 1
  • 5
  • 19

1 Answers1

1

You call setareaCode (I assume it's a useState hook) in the render and it causes one more re-render, then setareaCode changes again and re-render happens again, etc. As a result you would get an infinite loop. To fix it, try to avoid calling functions which cause re-renders. Instead of this, move this logic to useEffect hooks or callbacks.

Georgy
  • 1,879
  • 2
  • 9
  • 14
  • Okay, But I put like this ` useEffect(() => { if (watchAllFields.adultPassenger) { setareaCode(String(watchAllFields.adultPassenger[0]?.areaCode)); console.log(' state areaCode' + areaCode); } }, []); `. But state areCode do not change. Why? I am new to react. Please excuse If I am asking anything wrong. – hanushic Dec 18 '21 at 15:33