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>
)
}
Source: stackoverflow.com
Related Query
- Multiple markers on google map React with a .map
- Display Multiple Markers with Google Maps and React Js ES6
- How to show in a list, visible markers in the google map with React
- Multiple markers on google map from state variable React
- How can I use React with Google Places API, to display place markers on a Google map?
- Update Google Map based on Geolocation with React
- Using React state, how can I remove markers from a Google map before adding new ones?
- React Leaflet LayersControl.Overlay with multiple markers
- React Google Map and React Places Auto Complete: You have included the Google Maps JavaScript API multiple times on this page
- How to add map markers stored in a JSON feed to an existing React Google Map?
- Circle is not rendering on google map with React Google Map's API
- How to map multiple charts with chart.js in react
- Map multiple address with users json react js
- Apply changing markers array to Google map in react
- How to test material ui autocomplete google map with react testing library
- Launching multiple functions with map in react js
- Adding multiple markers to react google maps while using geocoder
- React JS Google Map Markers only shows after refresh
- how to add popup on google map with react leaflet?
- Keep updating markers on map on top of an overlay image - google maps react
- Google Maps in React don't show multiple markers
- Multiple Markers are not rendered in React Leaflet Map
- google maps integration with react js hooks, map flickers on update
- React with Google Maps Api, how to recenter map
- Retrieving value from <select> with multiple option in React
- Multiple params with React Router
- How target DOM with react useRef in map
- React Router v4 with multiple layouts
- Multiple classNames with CSS Modules and React
- Using google sign in button with react
More Query from same tag
- Javascript difficulty consuming promise values even after using await
- Is it common practice to grab store data from an action creator in flux?
- Handling Mapbox GeoJson lines across World Copies?
- mapDispatchToProps passess undefined props
- How to update data from child component to parent component using context api in react?
- Passing data up the components hierarchy in Modern React
- better way to return states within nested objects in a reducer
- React component Material UI withStyles: Variables in styles?
- Timer class based, Warning: Cannot update during an existing state transition (such as within `render`)
- user input to create pie chart using reactjs from form
- Syntax error: C:/Users/J/metafields-for-shopify/src/SettingsForm.js: Unexpected token, expected , (18:1)
- Create-react-app reload on service worker update
- How to filter by id?
- Find whether a React component is being displayed or not
- REACT how to store an Object instead of an Array of Objects in setState?
- React Chrome Extension - `chrome.tabs.executeScript` not consistent
- Can have simultaneously at onClick function props and a function at reactjs?
- Typescript inference for unions not picking up the correct type
- How to make an styled ReacJs Header component sticky or fixed on top?
- How To Call A JavaScript Function Returned From NodeJS in ReactJS JSX
- TypeError: nextCallback is not a function
- How to redirect a user to any page they try to access after authentication (conditional redirect)?
- React-google-maps: How do I create a clickable kml map that shows me meta data of the kml?
- typecast react typescript component class props
- How to properly use Sass with NextJS
- React state doesn't work, it doesn't rerender components
- Url Parameters not able to recieved in component in react Js when Passing Props with Route
- How to redirect to a new page from a function in React?
- React PureComponent pass paramater from Child component
- How to use Local modules in remix-run application in yarn workspaces