Uncaught TypeError: Cannot read properties of undefined but is defined
Solution 1:
The error message shows that the error is being thrown on this line:
searchResponse.results[num].place_id !== undefined
This will throw if searchResponse.results[num]
doesn't exist.
To be concise, try using optional chaining (and initialize searchResponse
to undefined or null). Do
const [searchResponse, setSearchResponse] = useState();
and change
if (
searchResponse !== "" &&
searchResponse.results[num].place_id !== undefined) {
setPlaceId(searchResponse.results[num].place_id);
to
const possiblePlaceId = searchResponse?.results[num]?.place_id;
if (possiblePlaceId) {
setPlaceId(possiblePlaceId);