Home > Software design >  How to create a counter that adds new data arrays every second in React js
How to create a counter that adds new data arrays every second in React js

Time:10-06

So I'm basically trying to make this constantly add new data arrays infinitely with a counter. So every second it should add a new one with the next number.

            data={[
          { x: 1, y: 1 },
          { x: 2, y: 2 },
          { x: 3, y: 3 },
          { x: 4, y: 4 },
          { x: 5, y: 5 },
          { x: 6, y: 6 },
        ]}

CodePudding user response:

let data=[]
function add_element(){
data.push({x:data.length, y:data.length})

}

setInterval(add_element, 1000);

for test purpose :

let data=[]
function add_element(){
data.push({x:data.length, y:data.length})
if(data.length==2) {
console.log(data)}
}

setInterval(add_element, 1000);

CodePudding user response:

const [data, setData] = useState([]);

useEffect(() => {
    const timer = setTimeout(() => {
                    setData((prev) => [...prev, { x: prev.length, y: prev.length }]);
                  }, 1000);
  
    return () => clearTimeout(timer);
  }, [data]);


// For testing purposes you can log the result in the console by
// uncommeting the following line:
// console.log(data);
  • Related