Skip to content

Instantly share code, notes, and snippets.

/App.js Secret

Created Jan 24, 2018
Embed
What would you like to do?
Array.prototype.map() method returns an empty array.
import React, { Component } from "react";
import jsonp from "jsonp";
// TThe list of streamers given.
const streamers = [ "freecodecamp", "ESL_SC2", "OgamingSC2", "cretetion", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas" ];
// Where the details of streamers will be saved.
const stream = [];
// The JSONP callback.
const callJSONP = streamer => {
// The Twitch.tv JSON API workaround provided by freeCodeCamp.
const api = `https://wind-bow.glitch.me/twitch-api/streams/${streamer}`;
let status = "Not Exist";
jsonp(api, (err, data) => {
try {
if (err) {
throw new Error("Something happened.");
}
if ( data.hasOwnProperty("stream") ) {
status = data["stream"] ? `${data["stream"]["game"]}: ${data["stream"]["channel"]["status"]}` : "Offline";
}
stream.push({ streamer, status });
} catch(err) {
console.log(err.message);
}
});
};
// The body of the table.
const TableBody = props => (
<tr key={props.streamer}>
<td> { props.streamer } </td>
<td> { props.status } </td>
</tr>
);
// The head of the table.
const TableHead = () => (
<thead>
<tr>
<th>Streamer</th>
<th>Status</th>
</tr>
</thead>
);
export default class App extends Component {
constructor(props) {
super(props);
// Populate the stream array.
streamers.forEach(callJSONP);
// Initialise the state object.
this.state = {
stream: stream
};
}
render() {
const stream = this.state.stream;
// The stream array is an array of objects,
// containing the names, and statuses of streamers.
console.log(stream);
const tbody = stream.map(TableBody);
// This is where the LOGICAL BUG is.
// The map method returns an empty array.
console.log(tbody);
return (
<table>
<TableHead />
<tbody>
{ tbody }
</tbody>
</table>
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.