I’m new to React and API calls. I currently have a list of locations being passed in as a prop to a Geocoder component which contains a geocoding function. This list is 17 objects long. My intent for this function is to convert all locations to a geocode, save them in a list, and plot them on a map. However, I have found myself stuck in an infinite loop of calls to the Google Maps Geocoder API and my geocodedLocations list becomes infinitely long.
I have planted many console.logs throughout my code and have figured that my the Geocoder component is not being called reptitively, but it is inside of the Geocoder component where this is happening. However, I will still provide the file where the component is being called just in case I’m wrong.
I have tried geocodedLocations a set in order to stop the infinite list problem. I have memoizing the props that are passed in to stop from repetetive data. None of these have stopped from the infinite API calls I get when passing in the list to the component
This is my code for the Geocoder component
import { APIProvider, useMapsLibrary } from "@vis.gl/react-google-maps";
import { memo, useState, useEffect } from "react";
// import MapsTool from "./MapsTool";
/* eslint-disable react/prop-types */
export default function Geocoder(locations) {
const locationList = locations.location;
const [geocodedLocations, setGeocodedLocations] = useState();
const addToGeocodedLocations = (newItem) => {
if (!geocodedLocations.includes(newItem)) {
setGeocodedLocations((prevList) => [...prevList, newItem]);
}
};
return (
<div>
<APIProvider apiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}>
{locationList.map((category, index) =>
category.map((categoryPart, innerIndex) => (
<Geocoding
key={`${index}-${innerIndex}`}
thing={categoryPart.thing}
city={categoryPart.city}
addGeoItem={addToGeocodedLocations}
/>
))
)}
</APIProvider>
{console.log("List of geolocations:" + JSON.stringify(geocodedLocations))}
</div>
);
}
const Geocoding = memo(function Geocoding({ thing, city, addGeoItem }) {
const fullAddress = thing + ", " + city;
const geocodingApiLoaded = useMapsLibrary("geocoding");
const [geocodingService, setGeocodingService] = useState();
const [address, setAddress] = useState("");
useEffect(() => {
if (!geocodingApiLoaded) return;
setGeocodingService(new window.google.maps.Geocoder());
setAddress(fullAddress);
}, [geocodingApiLoaded, fullAddress]);
useEffect(() => {
if (!geocodingService) return;
geocodingService.geocode({ address }, (results, status) => {
if (results && status === "OK") {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
addGeoItem({ lat, lng });
}
});
}, [geocodingService, address, addGeoItem]);
if (!geocodingService) return <div>loading...</div>;
return null;
});
This is my code to generate the prop that will be passed into the Geocoder
import { useState } from "react";
import { main } from "./tools/AILogic";
import AxiosInstance from "./tools/AxiosInstance";
import CitySelector from "./tools/CitySelector";
import DateSelector from "./tools/DateSelector";
import GuestsNumber from "./tools/GuestsNumber";
import BudgetNumber from "./tools/BudgetNumber";
import MapsTool from "./tools/MapsTool";
import Geocoder from "./tools/Geocoder";
const Generate = () => {
//dynamic states of page
const [loading, setLoading] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [mapLoad, setMapLoad] = useState(false);
// const [showChosenCity, setShowChosenCity] = useState(false);
const [allPlaceNames, setAllPlaceNames] = useState([]);
//user inputs to give to AI
const [selectedMonth, setSelectedMonth] = useState("");
const [selectedCity, setSelectedCity] = useState("");
const [adultNum, setAdultNum] = useState(0);
const [childNum, setChildNum] = useState(0);
const [infantNum, setInfantNum] = useState(0);
const [petNum, setPetNum] = useState(0);
const [dollarNum, setDollarNum] = useState("");
const [budget, setBudget] = useState("");
//data stored
const [content, setContent] = useState("");
const [title, setTitle] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
if (
selectedCity === "" ||
(petNum == 0 && childNum === 0 && adultNum === 0 && infantNum === 0) ||
(petNum != 0 && childNum === 0 && adultNum === 0 && infantNum === 0)
) {
console.log("fill out human categories or missing chosen city");
} else {
setMapLoad(false);
setSubmitted(true);
setLoading(true);
fetchData(
selectedCity,
selectedMonth,
adultNum,
childNum,
infantNum,
petNum,
budget,
dollarNum
);
}
};
const createSaved = (e) => {
e.preventDefault();
AxiosInstance.post(`saved/`, { content, title }).then(() =>
alert("saved!")
);
};
const handleCityChange = (city) => {
console.log(city);
setSelectedCity(city);
};
const handleMonthChange = (month) => {
console.log(month.getMonth() + 1);
setSelectedMonth(month.getMonth() + 1);
};
const handleGuestNumber = (adults, children, infants, pets) => {
console.log(adults, children, infants, pets);
setAdultNum(adults);
setChildNum(children);
setInfantNum(infants);
setPetNum(pets);
};
const handleBudget = (budget) => {
if (budget === "0-20$") {
setDollarNum("$");
} else if (budget === "20-40$") {
setDollarNum("$$");
} else if (budget === "40$+") {
setDollarNum("$$$");
}
setBudget(budget);
};
const fetchData = async (
city,
month,
adults,
children,
infants,
pets,
budget,
dollar
) => {
const JSONresponse = await main(
city,
month,
adults,
children,
infants,
pets,
budget,
dollar
);
setTitle(city);
console.log(JSONresponse);
setContent(JSON.parse(JSONresponse));
setLoading(false);
setMapLoad(true);
};
const restaurantList = content.restaurants;
const lodgingList = content.lodging;
const mallList = content.malls;
const placesList = content.places;
const formatCategories = () => {
const restaurantPlaceList = [];
restaurantList.map((thing) => {
restaurantPlaceList.push({ thing: thing[0], city: selectedCity });
});
const lodgingPlaceList = [];
lodgingList.map((thing) => {
lodgingPlaceList.push({ thing: thing[0], city: selectedCity });
});
const mallPlaceList = [];
mallList.map((thing) => {
mallPlaceList.push({ thing: thing[0], city: selectedCity });
});
const placesPlaceList = [];
placesList.map((thing) => {
placesPlaceList.push({ thing: thing[0], city: selectedCity });
});
const all = [
restaurantPlaceList,
lodgingPlaceList,
mallPlaceList,
placesPlaceList,
];
return <>{createMapMarkers(all)}</>;
};
const createMapMarkers = (list) => {
return <Geocoder location={list} />; // set to specific thing
};
return (
<>
<div className="generate-section">
<form onSubmit={handleSubmit} className="AI-form">
<CitySelector onInputChange={handleCityChange} />
<div className="calendar">
<DateSelector datePicked={handleMonthChange} />
</div>
<div className="guest-picker">
<GuestsNumber guestsNumber={handleGuestNumber} />
</div>
<div className="budget-chooser">
<BudgetNumber chosenBudget={handleBudget} />
</div>
<button type="submit" className="submit-ai">
Submit
</button>
</form>
{submitted ? (
<section>
{loading ? (
<p>loading...</p>
) : (
<div>
<button onClick={createSaved}>Save note!</button>
</div>
)}
</section>
) : null}
</div>
{mapLoad ? (
<div className="results-section">{formatCategories()}</div>
) : null}
</>
);
};
export default Generate;
Thank you in advance for the help.