Im new in reactjs I am receiving this error: "Error: Too many re-renders. React limits the number of renders to prevent an infinite loop." and I am not sure how to solved it.
const MAPBOX_TOKEN = ''; ///add token here
export default function MapHooks(){
const [mapping, setMapping] = useState({
width: 800,
height: 600,
longitude: -122.45,
latitude: 37.78,
zoom: 14
});
function _onViewportChange(mapping){
setMapping({mapping})
}
function _goToNYC() {
const viewport = {
...mapping,
longitude: 101.7412,
latitude: 3.1549,
zoom: 14,
transitionDuration: 5000,
transitionInterpolator: new FlyToInterpolator(),
transitionEasing: d3.easeCubic
};
setMapping({viewport})
}
return (
<div>
<button onClick={_goToNYC()}>New York City</button>
<MapGL
{...mapping}
mapStyle="mapbox://styles/mapbox/dark-v10"
onViewportChange={_onViewportChange()}
mapboxApiAccessToken={MAPBOX_TOKEN}
></MapGL>
</div>
);
}
Please help, thank you :)
You shouldn't be executing the function when assigning it to the onClick
, you should just be passing it in like so:
<button onClick={_goToNYC}>New York City</button>
If you actually call it when you assign it, then the function will execute. In that execution you call setMapping(...)
, which will trigger a re-render. Which will then cause that function to be executed again when the button renders, and so on -> infinite loop