1
I am carrying out a project of a Bootcamp and I came across this problem.
Error: Too Many re-renders. React Limits the number of renders to Prevent an Infinite loop.
The part that’s making a mistake is this:
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
dispatch(setRestaurants(results));
}
And the whole component is this:
import React, { useState, useEffect, useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { GoogleApiWrapper, Map, Marker } from 'google-maps-react';
import { setRestaurants, setRestaurant } from '../../redux/modules/restaurants';
export const MapContainer = (props) => {
const dispatch = useDispatch();
const { restaurants } = useSelector((state) => state.restaurants);
const [map, setMap] = useState(null);
const { google, query, placeId } = props;
const searchByQuery = useCallback(
(map, query) => {
const service = new google.maps.places.PlacesService(map);
const request = {
location: map.center,
radius: '2000',
type: ['restaurant'],
query,
};
service.textSearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
dispatch(setRestaurants(results));
}
});
},
[google, dispatch]
);
const getRestaurantById = useCallback(
(placeId) => {
const service = new google.maps.places.PlacesService(map);
const request = {
placeId,
fields: ['name', 'opening_hours', 'formatted_address', 'formatted_phone_number'],
};
service.getDetails(request, (place, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
dispatch(setRestaurant(place));
}
});
},
[google, map, dispatch]
);
useEffect(() => {
if (query) {
searchByQuery(map, query);
}
}, [map, query, searchByQuery]);
useEffect(() => {
if (placeId) {
getRestaurantById(placeId);
}
}, [placeId, getRestaurantById]);
const searchNearby = (map, center) => {
const service = new google.maps.places.PlacesService(map);
const request = {
location: center,
radius: '20000',
type: ['restaurant'],
};
service.nearbySearch(request, (results, status) => {
if (status === google.maps.places.PlacesServiceStatus.OK) {
dispatch(setRestaurants(results));
}
});
};
function onMapReady(_, map) {
setMap(map);
searchNearby(map, map.center);
}
return (
<Map
google={google}
centerAroundCurrentLocation
onReady={onMapReady}
onRecenter={onMapReady}
{...props}>
{restaurants.map((restaurant) => (
<Marker
key={restaurant.place_id}
name={restaurant.name}
position={{
lat: restaurant.geometry.location.lat(),
lng: restaurant.geometry.location.lng(),
}}
/>
))}
</Map>
);
};
export default GoogleApiWrapper({
apiKey: process.env.REACT_APP_GOOGLE_API_KEY,
language: 'pt-BR',
})(MapContainer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
I tried to put inside a Useeffect, but it was necessary in onMapReady