i am trying to generate random data in react.but data start to move like after 1 seconds 1 entry then after another second 5 entries then 26 then 126 and so on mean after every second data is exponentially generate.But i want to generate only 1 record after 1 second
function App() {
const [pktD,setPktD]=useState({
chid:0,
peakVal:0,
})
const dataGen=setInterval( function(){
setPktD({...pktD,chid:Math.random()*253});
setPktD({...pktD,peakVal:Math.random()*10000})
},5000)
console.log(dataGen);
return (
<></>
);
}
I also try to implement in custom hook but facing same problem.First entry generate after 5 second but after that data generate random intervals. myCustom hook is below i also tried this.
import React ,{useState} from "react"
function DataGenerator(){
const [pktD,setPktD]=useState({
chid:0,
peakVal:0
})
const dataGen=function(){
setPktD({...pktD,chid:Math.random()*253});
setPktD({...pktD,peakVal:Math.random()*10000})
return pktD
}
return [dataGen];
}
export default DataGenerator;
CodePudding user response:
You can do something like this
import React, { useState, useEffect } from "react";
function App() {
const [pktD, setPktD] = useState({
chid: 0,
peakVal: 0
});
useEffect(() => {
const dataGen = setInterval(function () {
// setPktD({ ...pktD, chid: Math.random() * 253 });
// setPktD({ ...pktD, peakVal: Math.random() * 10000 });
setPktD((prevState) => ({...prevState, chid: Math.random() * 253, peakVal: Math.random() * 10000}));
}, 5000);
return () => {
clearInterval(dataGen);
}
}, []);
console.log(pktD);
return <></>;
}
export default App;
CodePudding user response:
because you are not clearning interval along also use in useEffect beacuse its running async.