2

Before passing real time data of a fleet of vessels into a table after an API request, I wanted to try to inject sample data, in fact I hardcoded them. The goal would be: if I can read sample data, than almost surely the API will show the data into the table of all the vessels I am looking for.

However the debugger says that ErrorTypeError - Can't read property of indefined variable properly and the Console says:

Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }

ErrorTypeError: this is undefined if that is useful I am also including a screen-shot of my desktop:

console

Below the code I am using:

import React, { Component } from 'react';
import styled from 'styled-components';
import GoogleMapReact from 'google-map-react';

const resultArea = document.getElementById('result');
let out = '';

const fetchConfig = {
    method: 'GET',
    mode: 'no-cors'
};

const MapContainer = styled.div`
    // some components
`;

class BoatMap extends Component {
    constructor(props) {
        super(props);
        this.state = {
            buttonEnabled: true
        };
        this.updateRequest = this.updateRequest.bind(this);
    }

    updateRequest() {
        const url =
            'http://data.aishub.net/ws.php?username=My_KEY&format=1&output=json&compress=3&latmin=12.11&latmax=48.95&lonmin=-124.97&lonmax=-58.95';
        console.log(url);
        fetch(url, fetchConfig)
            .then(function(data) {
                console.log(data);
                return this.dummyData; // <-- Can't read this 
            })
            .then(function(jsonObject) {
                const boatData = JSON.parse(jsonObject);
                 for (boat in jsonObject) {
                    const boatInfo = [
                        // parsing data from the API after confirming with hardcoded dummyData
                     ];
                    boatOut(boatInfo);
                    console.log(boatInfo);
                 }
                resultArea.innerHTML = out;
            })
            .catch(function(e) {
                console.log('Error' + e);
            });
        this.setState({
            buttonEnabled: false
        });
        setTimeout(() => {
            this.setState({ buttonEnabled: true });
        });
    }

    dummyData = [
        {
            ERROR: false,
            USERNAME: 'My_KEY',
            FORMAT: 'HUMAN',
            LATITUDE_MIN: 20.5,
            LATITUDE_MAX: 30.8,
            LONGITUDE_MIN: -15,
            LONGITUDE_MAX: 18.6,
            RECORDS: 14
        },
        [
            {
                MMSI: 566619000,
                TIME: '2020-01-25 19:51:38 GMT',
                LONGITUDE: -14.84344,
                LATITUDE: 28.282,
                COG: 15.7,
                SOG: 11.3,
                HEADING: 16,
                ROT: 0,
                NAVSTAT: 0,
                IMO: 9529504,
                NAME: 'NORD SUMMIT',
                CALLSIGN: 'S6RW5',
                TYPE: 70,
                A: 174,
                B: 26,
                C: 20,
                D: 12,
                DRAUGHT: 12.1,
                DEST: 'NO SAU',
                ETA: '02-02 12:00'
            },
            {
                MMSI: 236446000,
                TIME: '2020-01-25 19:51:28 GMT',
                LONGITUDE: -14.83202,
                LATITUDE: 28.64639,
                COG: 38,
                SOG: 12.1,
                HEADING: 38,
                ROT: 3,
                NAVSTAT: 0,
                IMO: 9291561,
                NAME: 'KEY BAY',
                CALLSIGN: 'ZDIJ4',
                TYPE: 83,
                A: 82,
                B: 18,
                C: 1,
                D: 19,
                DRAUGHT: 6.1,
                DEST: 'CASABLANCA',
                ETA: '01-27 15:00'
            }
        ]
    ];

    render() {
        return (
            <div className="google-map">
                <GoogleMapReact
                    bootstrapURLKeys={{ key: 'My_KEY' }}
                    center={{
                        lat: 42.4,
                        lng: -71.1
                    }}
                    zoom={11}
                    <button className="btn-next-request" onClick={() => this.updateRequest()}>
                        Time to Next API Request
                    </button>
                </GoogleMapReact>
            </div>
        );
    }
}

What I have done so far:

1) I tried to solve the problem acting directly on the dummyDaya component trying to parse it manually. However the API already gives as answer the template file I included in the updateRequest() function. Nothing is shown.

2) I am not sure why I am not able to read the data of the two vessels as I copy/past the answer of the API for the two data. Technically it should be injected with no problem.

3) I am now trying to investigate the possibility that according to the official documentation the dummyData should not carry (and don't know if I should erase) the initial value of the request when passing the data. What I am referring to is the following part of the dummyData array:

dummyData = [
            {
                ERROR: false,
                USERNAME: 'My_KEY',
                FORMAT: 'HUMAN',
                LATITUDE_MIN: 20.5,
                LATITUDE_MAX: 30.8,
                LONGITUDE_MIN: -15,
                LONGITUDE_MAX: 18.6,
                RECORDS: 14
            },
[ …...

Thanks for pointing in the right direction for solving this problem.

1

3 Answers 3

1

Use arrow function to access this as component ref/instance. function has it's own this which will be misleading

fetch(url, fetchConfig)
    .then((data) => {
        console.log(data);
        return this.dummyData; // <-- Can't read this 
    })

Same applies to all such function in your code here

Sign up to request clarification or add additional context in comments.

Comments

1

First and foremost, if you wish to return the response from via fetch, you will need to call Body.json() to return the Response stream.

fetch(url, fetchConfig)
  .then((data) => {
     return data.json();
  }).then((data) => {
     console.log(data);
     // do the rest here
  }); 

Next, if you wish the reference this, you will need to use arrow functions,

fetch(url, fetchConfig)
  .then((data) => {
    return this.dummyData;
  }).then((data) => {
     console.log(data);
     // do the rest here
  }); 

Comments

0

Create state for dummyData.

constructor(props) {
   super(props);
   this.state = {
     buttonEnabled: true,
     dummyData : [],   // Create state for dummyData
   };
this.updateRequest = this.updateRequest.bind(this);
}

Then fetch data(I used async await) from your url and set it to dummyData.

const request = async () => {
         const url = 'http://data.aishub.net/ws.php? username=My_KEY&format=1&output=json&compress=3&latmin=12.11&latmax=48.95&lonmin=-124.97&l onmax=-58.95';

         const response = await fetch(url, fetchConfig);
         const json = await response.json();
         this.setState(dummyData : json);
    }        

    request();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.