Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda