I am struggling a bit with some react fundamentals, mainly the flow of data and the jsx syntax, sorry about the noob question.
I have two json that I am making chained api calls to in Main.js, the data is then passed down to SensorList.js. In this component I have a function that renders a list of sensors, each Sensor.js has it key set to an id specified in the json and has its props set based on the data in the json.
Currently I am able to grab the first corresponding piece of data for each sensor and pass this down to the relevant child components. I need to pass down the whole array of the corresponding data to a child Graph.js component, currently my map function is grabbing only the first element in each array.
My question is how do I actually pass down the whole arrays of the value and time data of each sensor to it's child graph component?
Thanks in advance.
sensors.json
[
{
"id": "46c634d04cc2fb4a4ee0f1596c5330328130ff80",
"name": "external"
},
{
"id": "d823cb4204c9715f5c811feaabeea45ce06736a0",
"name": "office"
},
{
"id": "437b3687100bcb77959a5fb6d0351b41972b1173",
"name": "common room"
}
]
Sample of data.json
[
{
"sensorId": "437b3687100bcb77959a5fb6d0351b41972b1173",
"time": 1472120033,
"value": 25.3
},
{
"sensorId": "437b3687100bcb77959a5fb6d0351b41972b1173",
"time": 1472119853,
"value": 25.1
},
{
"sensorId": "437b3687100bcb77959a5fb6d0351b41972b1173",
"time": 1472119673,
"value": 25.1
},
SensorList.js
var SensorList = React.createClass({
render: function() {
var {data, sensors} = this.props;
var renderSensors = () => {
return sensors.map((sensor) => {
return <Sensor key={sensor.id} name={sensor.name} value={data.get(sensor.id)}/>
});
};
return (
<div>
{renderSensors()}
</div>
);
}
});
Main.js
var Main = React.createClass({
getInitialState: function() {
return {
sensors: [],
sensorsData: []
};
},
componentDidMount: function() {
var _this = this;
this.serverRequest =
axios
.get("http://localhost:3000/sensors.json")
.then(function(result) {
_this.setState({
sensors: result.data
});
})
axios
.get("http://localhost:3000/data.json")
.then(function(result) {
var sensorDataToId = new Map();
for(var i = 0; i < result.length; i++) {
var datum = result[i];
var sensorId = datum.sensorId;
if (sensorDataToId.get(sensorId) === undefined) {
sensorDataToId.set(sensorId, []);
}
sensorDataToId.get(sensorId).push(datum)
}
_this.setState({
sensorsData: result.data
});
})
},
componentWillUnmount: function() {
this.serverRequest.abort();
},
render: function() {
var {sensors, sensorsData} = this.state;
return (
<div className="sensorList">
<SensorList sensors={sensors} data={sensorsData}/>
</div>
);
}
});