How to correctly handle route changes when using react-google-maps/api?

372 Views Asked by At

I have a react-router-dom router with following structure:

...
...
<BrowserRouter>
      ...
      <Switch>
          <Route exact path="/" component={Landing} />
          <Route path="/about" component={About} />
          <Route path="/dashboard" component={MyAccount} />
          <Route path="/register" component={Register} />
          <Route path="/login" component={Login} />
        </Switch>
</Router>
....

My Landing component conditionally displays a MapContainer component using @react-google-maps/api library:

import { GoogleMap, LoadScript, Marker, InfoWindow } from '@react-google-maps/api';

const containerStyle = {
  width: '100%',
  height: '400px'
};

const MapComponent = ({ trips }) => { 
  const [map, setMap] = useState(null);
  const [ selected, setSelected ] = useState({});
  const [ currentPosition, setCurrentPosition ] = useState({});

  const success = position => {
    const currentPosition = {
      lat: position.coords.latitude,
      lng: position.coords.longitude
    }
    setCurrentPosition(currentPosition);
  };

  const onSelect = item => {
    setSelected(item);
  };

  const onLoad = useCallback(function callback(map) {
    const bounds = new window.google.maps.LatLngBounds();
    map.fitBounds(bounds);
    setMap(map)
  }, []);

  const onUnmount = useCallback(function callback(map) {
    setMap(null)
  }, []);

  const getPosition = () => {
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej);
    });
  }

  const setPositionFromGeolocation = async () => {
    const res = await   getPosition();
    const currentPosition = {
      lat: res.coords.latitude,
      lng: res.coords.longitude
    }
    setCurrentPosition(currentPosition);
  }


  useEffect(() => {
    setPositionFromGeolocation(); 
  },[setPositionFromGeolocation]);
  
    return (
       <LoadScript
      googleMapsApiKey={process.env.REACT_APP_GOOGLE_MAPS_API_KEY}
    >
      <GoogleMap
        mapContainerStyle={containerStyle}
        center={currentPosition}
        zoom={2}
        onLoad={onLoad}
        onUnmount={onUnmount}
      >
        {Array.from(trips).map(trip => {
            const position = {
              lng: trip.geometry.coordinates[0],
              lat: trip.geometry.coordinates[1]
            }
              return (
              <Marker 
                key={trip._id}
                position={position}
                onClick={() => onSelect(trip)}
                />
              )
            })
        }
        {
            selected.geometry && (
              <InfoWindow
              position={{
                lng: selected.geometry.coordinates[0],
                lat: selected.geometry.coordinates[1] 
              }}
              clickable={true}
              onCloseClick={() => setSelected({})}
            >
              <p>{selected.description}</p>
            </InfoWindow>
            )
         }
        
      </GoogleMap>
    </LoadScript>
      
    );
}

When I change routes, I get these errors in console. I believe, that these errors are happening because I used navigator.geolocation.getCurrentPosition to get current user position with async/await syntax. Apart from try/catch that I forgot to add, may someone point out what am I missing or doing wrong?

1

There are 1 best solutions below

0
On BEST ANSWER

Turns out, I forgot to add trips prop to useEffect as dependency, that is being passed from Landing component to MapComponent component. So final version of the useEffect should be like this:

useEffect(() => {
    setPositionFromGeolocation(); 
  },[trips]);