Calling a seperate function from within useEffect in react

  const [markers, setMarkers] =  React.useState([]);

  const mapRef = React.useRef();

  React.useEffect( () => {
    fitBounds();
  }, [markers])

  const fitBounds = () => {
    const bounds = new window.google.maps.LatLngBounds();
    markers.map(place => {
      bounds.extend(place);
    });
    mapRef.current.fitBounds(bounds);
  };

In the above code snippet im trying to resize the map to the fit the window in which all markers can be seen. I want this to occur everytime a new marker is added so I though a good place to put it would be in the useEffect() function. However I keep getting the Error: TypeError: Cannot read property ‘fitBounds’ of undefined. Im fairly new to react so if someone could explain to me how I can achieve this functionality Id really appreciate it.

14 thoughts on “Calling a seperate function from within useEffect in react”

Leave a Comment