Reputation: 103
const measurements: { name: string, station: string, data: any[] }[] = [];
for (const selectedTrack of selectedTracks) {
for (const trackCircuitId of selectedTrack.tcIDs) {
await this.props.loadMeasurements(dateFrom, dateTo, trackCircuitId, selectedTrack.station);
console.log(this.props.measurements);
measurements.push({
name: trackCircuitId,
station: selectedTrack.station,
data: this.props.measurements
});
}
}
this.setState({
measurements: measurements,
refresh: false
});
await this.props.loadMeasurements(dateFrom, dateTo, trackCircuitId, selectedTrack.station);
Is calling for the action function and this.props.measurements is the prop that is returned by Redux! I'm trying to fill the measurements list and update its state when done and render a chart.
Atm. when I load data from this.props.measurements(...), this.props.measurements is async and empty. Which makes data always to be [].
Could use componentDidUpdate, but issue lies with the loops.
Upvotes: 0
Views: 47
Reputation: 1746
Try to use this custom loop function instead of for
const asyncForEach = async function (array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array)
}
}
const asyncLoop = async () => {
const measurements: { name: string, station: string, data: any[] }[] = [];
try {
await asyncForEach(selectedTracks, async selectedTrack => {
await asyncForEach(selectedTrack.tcIDs, async trackCircuitId => {
await this.props.loadMeasurements(dateFrom, dateTo, trackCircuitId, selectedTrack.station);
console.log(this.props.measurements) // If it works well
measurements.push({
name: trackCircuitId,
station: selectedTrack.station,
data: this.props.measurements
});
})
})
this.setState({
measurements,
refresh: false
});
} catch (err) {
console.log(err)
}
}
asyncLoop()
Upvotes: 1