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.

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

  1. I think the error is coming from this line within your fitBounds() function:

    mapRef.current.fitBounds(bounds);
    

    It’s likely trying to call it before the ref has finished setting.

    Try bailing out of the function early if it’s not ready, e.g.:

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

Leave a Comment