score:0

Accepted answer

you need to move your setlatlong(mydivelogs) inside the success method of api call. api call is async but assigning data in setlatlong is sync. react will push empty data in setlatlong.

you need to wait for api call and once data is available set the value in it.

import react, {
  usecontext,
  useeffect,
  usestate
} from 'react';
import {
  googlemap,
  useloadscript,
  marker
} from "@react-google-maps/api"
import settings from "../settings"
import mapsyles from "./mapstyles"
import {
  logcontext
} from '../divelog/divelogprovider';

export const maprender = (props) => {
  const {
    divelogs
  } = usecontext(logcontext)
  const [latlong, setlatlong] = usestate([])



  useeffect(() => {
    //taking the logs and running them through api to get lat and lng for each location 
    let mydivelogs = []
    divelogs.map(dl => {
      return fetch(`http://api.positionstack.com/v1/forward?access_key=mykey&query=${dl.location}&limit=1
            `)
        .then(res => res.json())
        .then(parsedres => {

          mydivelogs.push(parsedres.data[0])
          setlatlong(mydivelogs)
        })


    })

  }, [divelogs])

  // this returns several logs, the first of which are empty arrays and the last are correct with the data that i need
  console.log(latlong)




  const {
    isloaded,
    loaderror
  } = useloadscript({
    googlemapsapikey: settings.apikey
  })

  const mapcontainerstyle = {
    width: '31rem',
    height: '24rem'
  }

  const center = {
    lat: 0,
    lng: 0
  }

  const options = {
    styles: mapsyles,
    disabledefaultui: true
  }



  if (loaderror) console.log("error loading maps")
  if (!isloaded) return "loading..."

  return ( <
    div >
    <
    googlemap mapcontainerstyle = {
      mapcontainerstyle
    }
    options = {
      options
    }
    zoom = {
      1
    }
    center = {
      center
    } >

    {
      //this is where i map through the state variable
      latlong.map(l => ( <
        marker key = {
          l.lat
        }
        position = {
          {
            lat: l.latitude,
            lng: l.longitude
          }
        }
        />
      ))
    } <
    /googlemap> <
    /div>
  )
}


Related Query

More Query from same tag