I'm following this guide here: https://youtu.be/Pf7g32CwX_s on how to add a google map using react-google-maps. Code on Github: https://github.com/leighhalliday/google-maps-react-demo/blob/master/src/App.js
I have the example up and running, but now I want to fetch data from my backend instead of using a json file in frontend. So I have this setup:
App.js
import React from 'react';
export async function stationsDataFunction() {
const results = await fetch('http:...) ;
return results.json();
}
class App extends React.Component {
constructor(){
super();
this.state = {
}
}
render(){
return(
<div className="App">
<MapComponent/>
</div>
)
}
}
export default App;
MapComponent.js
import React, {useState} from 'react';
import { GoogleMap, Marker, withScriptjs, withGoogleMap, InfoWindow } from "react-google-maps"
import {stationsDataFunction} from './App';
function Map(){
console.log(stationsDataFunction()); // Line 14
const stationsData = stationsDataFunction().then(response => {console.log(response); return response;}); // Line 15
const [selectedStation, setSelectedStation] = useState(null);
return(
<GoogleMap // Line 19
defaultZoom={10}
defaultCenter={{ lat: 63.0503, lng: 21.705826}}
>
{stationsData.features.map(station => (
<Marker
key={station.properties.PARK_ID}
position={{
lat: station.geometry.coordinates[1],
lng: station.geometry.coordinates[0]
}}
onClick={(() => {
setSelectedStation(station);
})}
/>
))}
//... more code here
I'm returning data from backend to const stationsData but it seems like the response gets in too late. I get this error:
Uncaught TypeError: Cannot read property 'map' of undefined at Map (MapComponent.js:19)
Before the error the console prints out:
MapComponent.js:14 Promise {pending}
After the error the console prints out:
MapComponent.js:15 {type: "FeatureCollection", crs: {…}, features: Array(2)}
I can't figure out how to solve this problem.
UPDATE WITH WORKING CODE
App.js WORKING CODE
Exported function like this:
export async function stationsDataFunction() {
const results = await fetch('http://localhost:4000/api/myData/stationNames') ;
return results.json();
}
MapComponent.js WORKING CODE
import React, {useState, useEffect} from 'react';
import { GoogleMap, Marker, withScriptjs, withGoogleMap, InfoWindow } from "react-google-maps"
import {stationsDataFunction} from './App';
function Map(){
const [stationsData , setStationsData] = useState({ features: [] });
const [selectedStation, setSelectedStation] = useState(null);
async function fetchStationsData() {
const json = await stationsDataFunction();
setStationsData(json);
}
useEffect(() => {
fetchStationsData();
}, []);
return(
<GoogleMap
defaultZoom={10}
defaultCenter={{ lat: 63.0503, lng: 21.705826}}
>
{stationsData.features && stationsData.features.map(station => (
<Marker
key={station.properties.PARK_ID}
position={{
lat: station.geometry.coordinates[1],
lng: station.geometry.coordinates[0]
}}
// More code here