Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!