I have a api get call that has the dynamic json (values changing continuously).i currently store that data in new array.i am currently using setinterval to check for the new data in api. what happen is i got duplicate data pushed to my array since it check continuously on certain interval. until new data arrives it keeps pushing duplicate data to the array. please guide me how to approach this problem. i want to check the data before pushing i don't know how to do that. React Code:
this.interval =setInterval(() => {
fetch(`http://localhost:5000/api/2.0/mlflow/runs/get?run_id=sdgdfg`)
.then((response) => response.json())
.then(booksList => {
this.setState({ books: booksList.run.data.metrics});
})
let floors = [...this.state.dataPoints];
//push the values to new array
floors.push({
y: this.state.books[0].timestamp,
mAp: this.state.books[0].value
});
this.setState({ dataPoints:floors });
},150000)
CodePudding user response:
You have to check whether your new value already exists in your current array:
fetch(`http://localhost:5000/api/2.0/mlflow/runs/get?run_id=sdgdfg`)
.then((response) => response.json())
.then(booksList => {
this.setState({
books: booksList.run.data.metrics
});
});
let floors = [...this.state.dataPoints];
const newFloor = {
y: this.state.books[0].timestamp,
mAp: this.state.books[0].value
};
const alreadyExists = floors.some(floor => {
return floor.y === newFloor.y && floor.mAp === newFloor.mAp;
});
if (!alreadyExists) {
this.setState({
dataPoints: [...floors, newFloor]
});
}