Trigger google places api on button click instead of input change

I’m working on a React.js project using Material-UI (MUI), and I have a component where users need to enter their address. To minimize API costs, I want to trigger the Google Places API only when the user clicks a button, rather than on every input change.

Currently, I’ve set it up so that the API call happens when the button is clicked, but I’m running into two issues:

The Google Places autocomplete dropdown doesn’t appear immediately after the button click; it only shows up if the user clicks the input field again.
Even after implementing this, the Google API continues to make requests on every input change, which is what I’m trying to avoid.
How can I configure the component so that the Google Places API is triggered only once when the button is clicked, and the autocomplete dropdown shows up immediately, without any additional clicks or unwanted API calls?

import React, { useState, useEffect, useRef } from "react";
import {
  useMediaQuery,
  Box,
  Button,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  CircularProgress,
  Fade,
  FormControlLabel,
  Checkbox,
} from "@mui/material";

function Modal({ open, setOpen }) {
  const isUnder600px = useMediaQuery("(max-width:600px)");
  const isUnder1000px = useMediaQuery("(max-width:1000px)");
  const licensePlateInputRef = useRef(null);
  const addressInputRef = useRef(null);
  const autocompleteRef = useRef(null);

  const [data, setData] = useState({
    licensePlate: "",
    address: "",
  });
  const [loading, setLoading] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [isLicensePlateInputDisabled, setIsLicensePlateInputDisabled] = useState(false);
  const [inputKey, setInputKey] = useState(Date.now());

  let maxWidth;
  if (isUnder600px) {
    maxWidth = "xs";
  } else if (isUnder1000px) {
    maxWidth = "sm";
  } else {
    maxWidth = "md";
  }

  useEffect(() => {
    if (open && licensePlateInputRef.current) {
      licensePlateInputRef.current.focus();
    }
  }, [open]);

  const handleClose = (event, reason) => {
    if (reason && reason === "backdropClick") return;
    setOpen(false);
  };

  const handleChange = (e) => {
    const { name, value } = e.target;
    setData((prev) => ({
      ...prev,
      [name]: value,
    }));
  };

  const handleSearch = () => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
      setShowForm(true);
      setIsLicensePlateInputDisabled(true);
    }, 1500);
  };

  const handleSearchAddress = () => {
    setInputKey(Date.now()); // Update input key

    if (
      window.google &&
      addressInputRef.current &&
      !autocompleteRef.current
    ) {
      autocompleteRef.current = new window.google.maps.places.Autocomplete(
        addressInputRef.current,
        {
          types: ["address"],
          componentRestrictions: { country: "it" },
        }
      );

      // **Immediate Trigger (1): Set placeId to empty string**
      addressInputRef.current.placeId = "";

      // **Immediate Trigger (2): Simulate user input event**
      const inputEvent = new Event("input", { bubbles: true });
      addressInputRef.current.dispatchEvent(inputEvent);

      autocompleteRef.current.addListener("place_changed", () => {
        const place = autocompleteRef.current.getPlace();
        if (place && place.formatted_address) {
          setData((prev) => ({
            ...prev,
            address: place.formatted_address,
          }));
        }
      });

      addressInputRef.current.focus(); // Focus the input field
    }
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    handleSearch();
  };

  return (
    <Dialog
      open={open}
      onClose={handleClose}
      aria-labelledby="form-dialog-title"
      fullWidth={true}
      maxWidth={maxWidth}
      PaperProps={{
        sx: {
          maxWidth: showForm ? maxWidth : "400px",
          width: "100%",
          overflow: "visible",
        },
      }}
    >
      <DialogTitle id="form-dialog-title">
        {loading ? "Searching..." : "New Search"}
      </DialogTitle>
      <form onSubmit={handleSubmit}>
        <DialogContent>
          {loading ? (
            <Box
              sx={{
                display: "flex",
                justifyContent: "center",
                alignItems: "center",
                padding: "8px 0",
              }}
            >
              <CircularProgress />
            </Box>
          ) : (
            <>
              <Box
                sx={{
                  display: "flex",
                  flexDirection: maxWidth === "md" ? "row" : "column",
                  marginBottom: "8px",
                  marginTop: "8px",
                }}
              >
                <TextField
                  id={"licensePlate-input"}
                  disabled={isLicensePlateInputDisabled}
                  size="small"
                  label="License Plate"
                  name="licensePlate"
                  value={data.licensePlate}
                  onChange={handleChange}
                  fullWidth={!showForm}
                  inputRef={licensePlateInputRef}
                  autoFocus
                />
                {showForm && (
                  <Fade in={showForm}>
                    <Box
                      sx={{
                        display: "flex",
                        flexDirection: "column",
                        marginTop: maxWidth === "md" ? "0" : "8px",
                      }}
                    >
                      <Box ml={maxWidth === "md" ? 4 : 0}>
                        <FormControlLabel
                          control={
                            <Checkbox
                              sx={{
                                marginBottom: "3px",
                                margin: maxWidth === "xs" ? "8px 0" : " 0",
                              }}
                              defaultChecked={false}
                            />
                          }
                          label="Via Roma 56,199, Giugliano in Campania Na"
                        />
                        <Box sx={{ display: "flex", flexDirection: "row" }}>
                          <TextField
                            id={`address-input-${inputKey}`}
                            size="small"
                            label="Residential Address"
                            sx={{ width: "360px", marginRight: "16px" }}
                            error={false}
                            helperText={""}
                            value={data.address}
                            onChange={handleChange}
                            name="address"
                            InputProps={{
                              inputRef: addressInputRef,
                            }}
                          />
                          <Button
                            sx={{ maxHeight: "36px" }}
                            variant="contained"
                            onClick={handleSearchAddress}
                          >
                            {(maxWidth === "md") | "sm"
                              ? "Search Address"
                              : "Search"}
                          </Button>
                        </Box>
                      </Box>
                    </Box>
                  </Fade>
                )}
              </Box>
            </>
          )}
        </DialogContent>
        <DialogActions>
 
        </DialogActions>
      </form>
    </Dialog>
  );
}

export default Modal;


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