1

I built a boat visualizer using this API. After inquiring the API I am able to obtain a json response with the vessels I am interested in and write those API information into a MongoDB database.

The problem: Everything seems to be working well, but all of a sudden the application stops working throwing a strange error below. Now I researched a lot the possible cause:

TypeError: Cannot read property 'latLng' of undefined

what I don't understand in the error is that is pointing to a property that I dopn't have : latLng and that I only see in the node modules node_modules/react/cjs/react.development.js:1149

In my code I dont have latLng but I do have latlng (notice lowercase "l") and I showed it on my code below on async updateRequest() { ... }

I also took a print screen for completeness. The output carries some strange output from a node_modules/react/cjs/react.development.js:1149 and from the part of the code interested The last part of the error is my code BoatMap.updateRequest:

error

error2

server

var express = require('express');
var router = express.Router();
var axios = require('axios');
const NodeCache = require('node-cache');
const myCache = new NodeCache();

let hitCount = 0;

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', { title: 'Express' });
});

router.get('/hello', async function(req, res, next) {
    const allData = myCache.get('allData');

    if (!allData) {
        hitCount++;
        try {
            const { data } = await axios.get(
                'https://api.vesselfinder.com/vesselslist?userkey=KEY'
            );
            const { metaData, ships } = data;
            myCache.set('allData', data, 70);
            console.log(data + 'This is the data');
            res.send(data);
        } catch (error) {
            res.send(error);
            console.log(error);
        }
    }
    res.send(allData);
});

module.exports = router;

client

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ships: [],
            filteredShips: [],
            type: 'All',
            shipTypes: [],
            activeShipTypes: [],
            delayHandler: null,
            mapLoaded: false
        };
        this.updateRequest = this.updateRequest.bind(this);
    }

    async componentDidMount() {
        this.countDownInterval = setInterval(() => {
        }, 500);

        await this.updateRequest();

        this.updateInterval = setInterval(() => {
            this.updateRequest();
        }, 60 * 1000);
    }


    async updateRequest() {
        const url = 'http://localhost:3001/hello';
        const fetchingData = await fetch(url);
        const ships = await fetchingData.json();
        console.log('fetched ships', ships);

        if (JSON.stringify(ships) !== '{}') {
            if (this.previousTimeStamp === null) {
                this.previousTimeStamp = ships.reduce(function(obj, ship) {   
                    obj[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
                    return obj;
                }, {});
            }

            this.setState({
                ships: ships,
                filteredShips: ships
            });

            this.props.callbackFromParent(ships);

            for (let ship of ships) {
                if (this.previousTimeStamp !== null) {
                    if (this.previousTimeStamp[ship.AIS.NAME] === ship.AIS.TIMESTAMP) {
                        this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
                        console.log('Same timestamp: ', ship.AIS.NAME, ship.AIS.TIMESTAMP);
                        continue;
                    } else {
                        this.previousTimeStamp[ship.AIS.NAME] = ship.AIS.TIMESTAMP;
                    }
                }

                let _ship = {
                    // ships data ....
                };
                const requestOptions = {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(_ship)
                };
                await fetch('http://localhost:3001/users/vessles/map/latlng', requestOptions);
            }
        }
    }
}





render() {
    const noHoverOnShip = this.state.hoverOnActiveShip === null;
    // console.log("color", this.state.trajectoryColor);
    return (
        <div className="google-map">
            <GoogleMapReact
                // ships={this.state.ships}
                bootstrapURLKeys={{ key: 'key' }}
                center={{
                    lat: this.props.activeShip ? this.props.activeShip.latitude : 37.99,
                    lng: this.props.activeShip ? this.props.activeShip.longitude : -97.31
                }}
                zoom={5.5}
                onGoogleApiLoaded={({ map, maps }) => {
                    this.map = map;
                    this.maps = maps;
                    // we need this setState to force the first mapcontrol render
                    this.setState({ mapControlShouldRender: true, mapLoaded: true });
                }}
            >
                {this.state.mapLoaded ? (
                    <div>
                        <Polyline
                            map={this.map}
                            maps={this.maps}
                            markers={this.state.trajectoryData}
                            lineColor={this.state.trajectoryColor}
                        />
                    </div>
                ) : (
                    ''
                )}

                {/* Rendering all the markers here */}
                    {Array.isArray(this.state.filteredShips) ? (
                        this.state.filteredShips.map((ship) => (
                            <Ship
                                ship={ship}
                                key={ship.AIS.MMSI}
                                lat={ship.AIS.LATITUDE}
                                lng={ship.AIS.LONGITUDE}
                                logoMap={this.state.logoMap}
                                logoClick={this.handleMarkerClick}
                                logoHoverOn={this.handleMarkerHoverOnShip}
                                logoHoverOff={this.handleMarkerHoverOffInfoWin}
                            />
                        ))
                    ) : (
                        'Loading...'
                    )}

                </GoogleMapReact>
        </div>
    );
}

What I have done so far:

1) I also came across this source to help me solve the problem but no luck.

2) Also I consulted this other source, and also this one but both of them did not help me to figure out what the problem might be.

3) I dug more into the problem and found this source too.

4) I read this one too. However, neither of these has helped me fix the problem.

5) I also found this source very useful but still no solution.

Thanls for pointing to the right direction for solving this problem.

Emanuele
  • 2,194
  • 6
  • 32
  • 71

1 Answers1

1

I found the same issue here related to google-map-react.

looking at your code your fallback is plain string (inside your GoogleMapReact component), and that would be causing the error when it should be a component.

edit: your component GoogleMapReact also doesnt look closed (maybe missed from pasting the code)

I would use the && operator like:

 { this.state.mapLoaded && (
                    <div>
                        <Polyline
                            map={this.map}
                            maps={this.maps}
                            markers={this.state.trajectoryData}
                            lineColor={this.state.trajectoryColor}
                        />
                    </div>) 
}

for the <Ship> logic I would try at first wrap <div>Loading...</div>, but I would guess that google-map-react might not accept that. If it doesnt I would use the same approach with &&.

buzatto
  • 9,704
  • 5
  • 24
  • 33
  • thanks for stopping by and reading the question :) Could you please integrate your answer with some code so that I can better understand your suggestion? – Emanuele Jun 17 '20 at 14:22
  • Thanks for the update. Yes from copy/paste I missed the closing part of the statements in fact. I updated the question for completeness. – Emanuele Jun 17 '20 at 15:07
  • Ok I will give a try to your suggestion and let you know. Thanks for your time in reading/answering! :) – Emanuele Jun 17 '20 at 15:08
  • Hey I just wanted to let you know that your suggestion worked. The application does not stop anymore on that point. Also `
    Loading...
    ` did the trick! thanks for your help :)
    – Emanuele Jun 18 '20 at 18:26