Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
NextJS - React google maps api - infinite loop

trying to figure out why my react function component map is infinite looping and continuously rerendering the map. i've stared at this for a while and am thinking it has to do with the useEffects but I can't seem to fix it.. attached is screenshot of error and the map component code. let me know if you need to see other code

screenshot of error

  useJsApiLoader,
  GoogleMap,
  DirectionsRenderer,
} from "@react-google-maps/api";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Box } from "@chakra-ui/react";
import { useDebouncedCallback } from "../../hooks/useDebouncedCallback";

export default function Map(props) {
  const router = useRouter();
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
    id: "google-map-script",
  });

  const [map, setMap] = useState(/** @type google.maps.Map */ (null));
  const [directionsResponse, setDirectionsResponse] = useState(null);

  async function calculateRoute() {
    /* eslint-disable */
    const directionsService = new google.maps.DirectionsService();
    /* eslint-disable */
    const results = await directionsService.route({
      origin: props.from,
      destination: props.to,
      /* eslint-disable */
      travelMode: google.maps.TravelMode.DRIVING,
    });

    console.log(results);
    setDirectionsResponse(results);
  }

  useEffect(() => {
    console.log("useEffect fired!", { asPath: router.asPath });
    calculateRoute();
  }, [router.asPath]);

  useEffect(() => {
    calculateRoute();
  });

  if (!isLoaded) {
    return <div>ligma</div>;
  }
  return (
    <GoogleMap
      center={directionsResponse}
      zoom={15}
      mapContainerStyle={{
        width: props.width,
        height: props.height,
        borderRadius: "20px",
      }}
      options={{
        zoomControl: false,
        streetViewControl: false,
        mapTypeControl: false,
        fullscreenControl: false,
      }}
      onLoad={(map) => setMap(map)}
    >
      <DirectionsRenderer directions={directionsResponse} />
    </GoogleMap>
  );
}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

To address your concern regarding the loop, I would begin by removing the duplicate:

useEffect(() => {
    calculateRoute();
  });

The error that is displayed is specifying that the LatLngLiteral coordinates received when the API attempts to center the map, are not a number. Consider using console.log(isNan(directionsResponse)) to check whether the value is a number, which is required for setCenter error to resolve. If directionsResponse is not a number, consider using center=parseFloat(directionsResponse). This issue appears separate to your looping concern.

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda