I have written a function which is triggered by a dropdown list's onChange event. Once the function is triggered, it load data from rest API according to the parameter value. However, the array which I have used to store those data is not cleared in the subsequent dropdown change events. As a result, when the user change the dropdown multiple times, the array grows with its previously loaded data.
for example: In first drop down change => ['A','B','C'] 2nd drop down change => ['A','B','C','E','F','G'] instead of ['E','F','G']
My code is as follows:
onDropdownChange = (e) => {
var newArray = [];
// To remove all the elements of newArray
newArray.forEach((e1,idx, arr) => {
newArray.splice(idx,1);
});
console.log(newArray);
const url = 'https://abcdefgh...../' + e + '/readings?today';
newArray = this.state.data.slice();
axios.get(url).then(res => {
var response_arr = res.data.items;
res.data.items.forEach((item, index) => {
newArray.push({ time: res.data.items[index].dateTime, TM: res.data.items[index].value })
})
let sortedArray = newArray.sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
this.setState({ data: sortedArray });
this.fetchChart();
});
}
fetchChart = () => {
const { data } = this.state;
return <CustomLineChart data={data} />
}
render(){
const {items} = this.state;
var data = [];
const itemList = items.map(item => {
return <tr key={item.dateTime+''+item.value}>
<td style={{whiteSpace: 'nowrap'}}>{item.dateTime}</td>
<td>{item.measure}</td>
<td>{item.value}</td>
</tr>
});
return (
<div>
{this.fetchChart()}
<CustomDropdownList changeLink={this.onDropdownChange.bind(this)} />
</div>
);
}
}
export default Dashboard;
Can anybody assist me to resolve this issue?