2
votes

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
2

2 Answers

1
votes

That's right, the data is not yet loaded once the markers are getting rendered.

The list of changes:

a) init default value like this (to prevent 'map' of undefined error):

const [stationsData, setStationsData] = useState({ features: [] });

b) use Effect Hook to fetch data:

useEffect(() => {
   fetchStationsData();
}, []);

where

async function fetchStationsData() {
   const json = await stationsDataFunction();
   setStationsData(json);
}

Example

function Map(props) {
  const [data, setData] = useState([{ features: [] }]);

  async function fetchData() {
    const results = await fetch(
      "https://raw.githubusercontent.com/leighhalliday/google-maps-react-demo/master/src/data/skateboard-parks.json"
    );
    const json = await results.json();
    setData(json.features)
  }

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <GoogleMap defaultZoom={props.zoom} defaultCenter={props.center}>
      {data.map(item => (
        <Marker key={item.properties.PARK_ID} position={{
          lat: item.geometry.coordinates[1], 
          lng: item.geometry.coordinates[0]
        }} />
      ))}
    </GoogleMap>
  );
}
0
votes

The problem in your code is that you have a async call here

const stationsData = stationsDataFunction().then(response => {console.log(response); return response;});

But when you try to access the data stationsData.features, features is undefined because the promise didn't resolve yet.

What you can do is conditinal rendering

{stationsData.features && stationsData.features.map(...)}

But maybe, this wont solve your problem and you will need to use useEffect hook.

import React, {useState, useEffect} from 'react';

function Map(){
    const [stationsData , setStationsData] = useState({}); 
    const [selectedStation, setSelectedStation] = useState(null); 

    useEffect(() => { 
        stationsDataFunction().then(response => {console.log(response); setStationsData(response);});
    }, [])

    return(
        <GoogleMap // Line 19
            defaultZoom={10}
            defaultCenter={{ lat: 63.0503, lng: 21.705826}}
        >
            {stationsData.features && stationsData.features.map(...)
        ...