I built a boat visualizer using specific 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 and show the vessels icons on a Google Map
.
The API has a 1 minute query limit, therefore to bypass the problem I set an automatic counter to 1 minute and 5 seconds and after that I launch the request.
The problem: The applications works great but if I manually refresh the page too many times within 1 minute I get the following error:
Unhandled Rejection (TypeError): ships.reduce is not a function
Below a print screen of the error:
Below the code:
class BoatMap extends Component {
constructor(props) {
super(props);
this.state = {
ships: [],
filteredShips: [],
type: 'All',
shipTypes: [],
activeShipTypes: [],
mapControlShouldRender: false,
mapLoaded: false
};
this.updateRequest = this.updateRequest.bind(this);
this.countDownInterval = null;
this.updateInterval = null;
this.map = null;
this.maps = null;
this.previousTimeStamp = null;
}
// Timed request
async componentDidMount() {
this.countDownInterval = setInterval(() => {}, 500);
await this.updateRequest();
this.updateInterval = setInterval(() => {
this.updateRequest();
// Operate automatic request every 1 minute and 5 seconds
}, 65 * 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) { // <-- Error Here
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 info .....
};
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(_ship)
};
await fetch('http://localhost:3001/users/vessles/map/latlng', requestOptions);
// console.log('Post', Date());
}
}
}
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.
Thank you very much for pointing to the right direction for solving this issue.