i am currently trying to fetch this 2 api which consist of different table in my database. i will compare the data and the threshold of the sensors to make sure that the threshold do not exceed the threshold. but my second fetch call is making it render twice. giving 2 same output instead of one
const TempGraph = () => {
const [data, setData] = useState([]); // sound , temp, humidity , light , motion .
const [thresholddata,setThresholdData] = useState([]);
var result = [];
// var i = 0;
//const thresholds = '35';
function addZero(i) {
if (i < 10) {i = "0" + i}
return i;
}
useEffect(() => {
const interval = setInterval(() => asyncFetch(),5000) //5000ms = 5sec
return () => clearInterval(interval) // clear the interval everytime
}, []);
/* fetch specific sensor type */
const asyncFetch = async() => {
await fetch('api')
.then((response) => response.json())
.then((json) => setData(
(json || []).map((item) => {
const timeStamp = new Date(item.time);
return {
...item,
time: `${addZero(timeStamp.getHours())}:${addZero(timeStamp.getMinutes())}`,
};
})
)
)
.catch((error) => {
console.log('fetch data failed', error);
});
//fetching threshold data
await fetch('api')
.then((response) => response.json())
.then((json)=>setThresholdData(json))
.catch((error) => {
console.log('fetch threshold data failed',error);
});
};
if(data.length != 0){
/* Loop through threshold table to get the same type id */
for(var x =0;x<thresholddata.length;x++){
// console.log(thresholddata[i])
if(thresholddata[x].typeid == data[data.length-1].typeid && thresholddata[x].sensorid == data[data.length-1].sensorid){
result = thresholddata[x];
console.log(result)
}
}
/* notification when the data value is over the threshold */
if(result.upperthreshold < data[data.length-1].value){
openNotificationWithIcon('warning',data[data.length-1].location);
}
}
/* graph here */
}