0

I'm learning React and doing a practice task. I need to generate numbers every (time interval), which I did like this.

 import React, { useEffect, useState } from "react";

const SalesGenerator = () => {
  const [number, setNumber] = useState(0);
  //   let salesArr = [];
  useEffect(() => {
   
    const interval = setInterval(
      () => setNumber(Math.floor(Math.random() * 50 + 1)),
      1000,
    );

    // clean up interval on unmount
    return () => {
      clearInterval(interval);
    };
  }, []);

  return (
    <div>
      <p>{number}</p>
    </div>
  );
};

export default SalesGenerator;

How do I grab every generated number and push it into an array. I understand this is the step I need to get to in order to use the array/object to generate a chart to visualise that data.

1 Answer 1

1

Something like this

const [number, setNumber] = useState(0);

  const [list, setList] = useState([]);
  useEffect(() => {
    const interval = setInterval(
      () => setNumber(Math.floor(Math.random() * 50 + 1)),
      1000,
    );
    // clean up interval on unmount
    return () => {
      clearInterval(interval);
    };
  }, []);

  useEffect(() => {
    setList([...list, number])
  }, [number])
  return (
    <div>
      <p>{list}</p>
    </div>
  );

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, Yi Zhou. It makes a lot of sense, but somehow doesn't work. :(
My bad, you will need two useEffect in order to get working, one to track random number and one to push to list
So cool, Yi Zhou! It did not occur to me to use two useEffects and two state hooks for each element. I tried to shove it all into one useEffect. Great answer! Makes perfect sense.
seems to me like bad practice...

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.