1

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;

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

3 Comments

kindly also explain my code problem and solution.
another thing.i dont want to generate data on useEffect.because it will run first time.Actually i want to make it like a real time data simulation which generate data after every second without reloading.
The problem with your code is that the setInterval updates the state which will trigger rerender which then creates a new interval. So, basically on every rerender the new setInterval will be created. The right way to do this would be to use useEffect which will register the setInterval once.
1

because you are not clearning interval along also use in useEffect beacuse its running async.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.