why react-hook-form doesn’t see on Submit next.js

I’m working on setting up the server now. I want to make it possible to edit my form. With the usual functionality, everything works fine, when you just need to add an address, POSTs are sent and the data is updated. But when it comes to changing the data that I previously passed to initialData, problems begin. onSubmit simply refuses to compile, although I checked the arrival of data 100 times and initialData passes all the data for initialization.

const AddPointMap = ({ isOpen, onClose, onSubmitAddress, center, type, typeOfButton, initialData }) => {
  const [isLoaded, setIsLoaded] = useState(false);
  const [loadError, setLoadError] = useState(null);
  const [marker, setMarker] = useState(null);
  const [capacityValue, setCapacityValue] = useState('');

  const loader = new Loader({
    apiKey: GOOGLE_MAPS_API_KEY ?? '',
    version: 'weekly',
    libraries,
    id: 'google-map-script',
  });

  const { register, handleSubmit, setValue, control, formState: { errors }, reset } = useForm();
  const [selectedValue, setSelectedValue] = useState(null);

  useEffect(() => {
    if (initialData) {
      console.log('Initial Data:', initialData);
      setValue('name', initialData.Name || '');
      setValue('comment', initialData.Comment || '');
      setValue('primaryFirstName', initialData.PrimaryFirstName || '');
      setValue('primaryLastName', initialData.PrimaryLastName || '');
      setValue('primaryPhonNumber', initialData.PrimaryPhonNumber || '');
      setValue('capacity', initialData.Capacity || '');
      setMarker({
        lat: initialData.Lat || 0,
        long: initialData.Long || 0,
      });
      setCapacityValue(initialData.Capacity || '');
    } else {
      reset({
        name: '',
        capacity: '',
        comment: '',
        primaryFirstName: '',
        primaryLastName: '',
        primaryPhonNumber: '',
        select: '',
      });
      setMarker(null);
      setCapacityValue('');
    }
  }, [isOpen, initialData, reset, setValue, control]);
  
  
  const onSubmit = async (data) => {
    console.log(data);
    const completeData = {
      name: data.name,
      lat: marker?.lat || 0,
      long: marker?.long || 0,
      capacity: data.capacity,
      comment: data.comment,
      primaryFirstName: data.primaryFirstName,
      primaryLastName: data.primaryLastName,
      primaryPhonNumber: data.primaryPhonNumber,
      type: type === 'Oil' ? '1' : '2'
    };
  
    let result;
    if (initialData) {
      result = await updateCompanyLocation(initialData.Id, completeData); // Обновление адреса
    } else {
      console.log(completeData);
      result = await createCompanyLocation(completeData); // Создание нового адреса
    }
  
    if (result.success) {
      onSubmitAddress(result.data);
    } else {
      console.error(result.message);
    }
  
    onClose();
    reset();
    setMarker(null);
    setValue("primaryPhonNumber", "");
    setValue('capacity', '');
  };
  

  useEffect(() => {
    loader
      .load()
      .then(() => setIsLoaded(true))
      .catch((error) => setLoadError(error));
  }, [loader]);

  const handleMapClick = useCallback((event) => {
    const lat = event.latLng.lat();
    const long = event.latLng.lng();
    setMarker({ lat, long });
  }, []);

  const onCancel = () => {
    onClose();
    reset();
    setMarker(null);
    setSelectedValue(null);
  };

  if (loadError) {
    return <div>Error loading Google Maps</div>;
  }

  if (!isLoaded) {
    return <div>Loading Google Maps...</div>;
  }

  return (
    <>
      <Modal
        isOpen={isOpen}
        onRequestClose={onClose}
        contentLabel="Add Operational Address"
        ariaHideApp={false}
        style={{ 
          overlay: { backgroundColor: 'rgba(31, 34, 41, 0.8)' }, 
          content: { borderRadius: '10px' }  
        }}
      >
        <div className={styles.title}>
          <h2>{type} {type === "Oil" ? 'Container Location' : 'Location'}</h2>    
          <button onClick={onClose}><IoClose size={34}/></button>
        </div>
        <GoogleMap
          id="google-map"
          mapContainerStyle={containerStyle}
          center={center}
          zoom={16}
          onClick={handleMapClick}
        >
          {marker && (
            <OverlayView
              position={{ lat: marker.lat, lng: marker.long }}
              mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}
            >
              <FaMapMarkerAlt size={24} />
            </OverlayView>
          )}
        </GoogleMap>
      <form className={styles.dialogForm} onSubmit={handleSubmit(onSubmit)}>
        <label className={styles.smallText}>{type} Location Name:</label>
          <input 
            className={`${styles.formInput} ${errors.name && styles.inputError}`} 
            placeholder="Enter name" 
            {...register("name", { required: true })}
          />
          <label className={styles.smallText}>Location coordinates:</label>
          { marker && (
            <div className={styles.selectAdress}>
              {marker.lat}, {marker.long}
            </div>
          )}
          {!marker && (
            <>
              <input 
                className={`${styles.formInput} ${errors.selectAdress && styles.inputError}`} 
                type="text" 
                placeholder="Put a point on the map" 
                disabled={true}
                {...register("selectAdress", { required: true })}
              />
            </>
          )}
          <label className={styles.smallText}>{type === 'Oil' ? 'Coocking Oil' : 'Grease Trap'} Capacity:</label>
          <div className={errors.capacity && styles.inputError}>
            <Controller
              name="capacity"
              control={control}
              rules={{ required: true }}
              render={({ field }) => (
                <CustomSelector
                  options={options}
                  select={type === 'Oil' ? 'Oil Capacity' : 'Trap Capacity'}
                  selectValue={(value) => {
                    setSelectedValue(value);
                    field.onChange(value);
                  }}
                  initialValue={capacityValue}
                />
              )}
            />
          </div>
          <label className={styles.smallText}>{type === 'Oil' ? 'Oil' : 'Trap'} Location Comments:</label>
          <textarea 
            className={`${styles.textareaInput} ${errors.comment && styles.inputError}`} 
            placeholder="Enter text" 
            rows="6" 
            {...register("comment", { required: true })} 
          />
          <label className={styles.smallText}>Primary contact person:</label>
          <div className={styles.personInput}>
            <input 
              className={`${styles.formInput} ${errors.primaryFirstName && styles.inputError}`} 
              type="text" 
              placeholder="First Name" 
              {...register("primaryFirstName", { required: true })} 
            />
            <input 
              className={`${styles.formInput} ${errors.primaryLastName && styles.inputError}`} 
              type="text" 
              placeholder="Last Name" 
              {...register("primaryLastName", { required: true })} 
            />
          </div>
          
          <label className={styles.smallText}>Contact number:</label>
          <Controller
            name="primaryPhonNumber"
            control={control}
            rules={{ required: true }}
            render={({ field }) => (
              <PhoneInput
                {...field}
                className={errors.primaryPhonNumber ? styles.numberInputError : styles.numberInput}
                defaultCountry="US"
                placeholder="Enter phone number"
                onChange={(value) => {
                  console.log('Phone Number Changed:', value);
                  field.onChange(value);
                }}
                limitMaxLength={10}
              />
            )}
          />
          
          <div className={styles.submitButtons}>
            <button className={styles.cancel} type='button' onClick={onCancel}>Cancel</button>
            <button type="submit">Add {typeOfButton} <GoPlusCircle size={24} /></button>
          </div>
        </form>
      </Modal>
    </>
  );
};

export default React.memo(AddPointMap);

I checked console.log() and tried to wrap handleSubmit in other functions in which to call onSubmit

New contributor

Patrik is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật