I have to perform multiple fetch queries. Based on my first query i have make to make a multiple other queries after receiving all the i should be able to assign the data to the react component state. It appears that i am assigning the values to the component state before the fetch method is finished and hence they appear empty array.
I have tried by removing the inner fetch method outside and performing the query.
import React, { Component } from 'react';
import './App.css';
import Sensors from './iot/Sensors';
class App extends Component {
constructor (props) {
super (props);
this.state = {
status: 'disconnected',
devices: [],
dataPoints: []
};
}
componentDidMount() {
// Get Zigbee devices
fetch('http://localhost:3000/ssapi/zb/dev')
.then((res) => res.json())
.then((data) => {
this.setState({
devices : data
})
data.map((device) => {
const dataPoint = []
JSON.parse(device.metadata).dataGroups.map((datagroup) =>{
const url = 'http://localhost:3000/ssapi/zb/dev/' + device.id + '/ldev/' + datagroup.ldevKey + '/data/' + datagroup.dpKey;
fetch(url)
.then((res) => res.json())
.then((data) =>{
dataPoint.concat(data)
console.log('Data', data);
console.log('Inside dataPoint', dataPoint);
})
.catch((error) => console.log(error));
}) // dataGroups.map
console.log("Final dataPoint", dataPoint);
const dataPoints = this.state.dataPoints.concat(dataPoint);
this.setState({ dataPoints });
}) // data.map
}) // fetch
.catch((error) => console.log(error));
}
render() {
console.log('Render Devices', this.state.devices);
console.log('Render dataPoints', this.state.dataPoints);
}][1]][1]
I am expecting a final component states that look like this or in render function - console logging should look like this.
devices = [{},{},{},{},{}...]
dataPoints = [[{},{},{},..], [{},{},{},..], [{},{},{},..], ....]