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

181
Visualizações
Same array inside of useEffect and getCoordinates is different when console.log

Using GoogleMap API to display custom locations

I have an array of json object called data imported; it has a property called address. Google map api looks up coordinates of the address property and should generates custom Markers from an array called locations.

But the value of locations inside fetchLocations() and getCoordinates, are different when I console.log, although the both represent the same variable.

What did I do wrong?

import React, { useEffect, useState } from 'react'
import { GoogleMap, useLoadScript, InfoWindowF, MarkerF } from "@react-google-maps/api"
import { data } from './data'

const API_KEY = "1234567890"

export default function MyComponent() {

  const { isLoaded }: any = useLoadScript({
    googleMapsApiKey: API_KEY,
  })

  const result : any[] = [];
  const [locations, setLocations] = useState(result);

  useEffect(() => {
    const fetchLocations = async () => {
      const locations = await Promise.all(data.map(getCoordinates));
      console.log("Locations in fetchLocations", locations)
    };
    fetchLocations();
  }, []);


const getCoordinates = async (obj: any) => {
  const objData = await fetch("https://maps.googleapis.com/maps/api/geocode/json?address=" + obj.address + '&key=' + API_KEY)
  const response = await objData.json()
      const latitude = response.results[0].geometry.location.lat;
      const longitude = response.results[0].geometry.location.lng;
      const position = { 'lat': latitude, 'lng': longitude }
      locations.push(position)
      console.log("Locations in get Cooordinate", locations)
}


  if (!isLoaded) return <div>Loading...</div>
  return (
    <div className='flex flex-col'>
      <GoogleMap
        zoom={11}
        center={{ lat: 35.685661305110415, lng: 139.75255896834707 }}
        mapContainerClassName='w-full h-[32em] m-2 rounded-lg'
      >
        <>
          {locations.map(location=>{
            return(
              <>
                <MarkerF
                  position={{ lat: location.lat, lng: location.lng }}
                />              
              </>
            )
          })
          }        
        </>
      </GoogleMap>
      <button onClick={() => { setSelected(!selected) }}>Click</button>
    </div>
  )
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The locations array should never be changed in any way. It's supposed to be immutable. The only thing that is able to change it is the setLocations function.

Instead of locations.push(position) do:

setLocations([...locations, position])

Also, getCoordinates is not returning anything. It should return the same value sent to setLocations:

return [...locations, position]
about 4 years ago · Juan Pablo Isaza 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