Home > Enterprise >  async await function in useEffect returns same data on loop
async await function in useEffect returns same data on loop

Time:01-25

I'm fetching svgs from multiavatar api but the issue is when i write the function in useEffect it gives me same value four times. But when i make the useEffect async it shows me different values.

I just want to know why it is happening?

It is showing me 4 different images.

 useEffect(async () => {
    const data = [];
    for (let i = 0; i < 4; i  ) {
      const image = await axios.get(
        `${api}/${Math.round(Math.random() * 1000)}`
      );
      const buffer = new Buffer(image.data);
      data.push(buffer.toString("base64"));
    }
    setAvatars(data);
    setIsLoading(false);
  }, []);

This shows me same image 4 times

  useEffect(() => {
    const loadData = async () => {
      const data = [];
      for (let i = 0; i < 4; i  ) {
        const image = await axios.get(
          `${api}/${Math.round(Math.random) * 1000}`
        );
        const buffer = new Buffer(image.data);
        data.push(buffer.toString("base64"));
      }
      setAvatars(data);
      setIsLoading(false);
    };

    loadData();
  }, []);

CodePudding user response:

The random number generator is seeded using a value based on the system clock.

This means that if you're creating two Random instances shortly after each other, they will be initialized using the same value, because the system clock has a finite resolution. Having the same seed means that these two instances will produce the same sequence of results.

Try creating the random values outside of the sync function or using random.next

CodePudding user response:

The random number was not generating because of syntax error.

  useEffect(() => {
    const loadData = async () => {
      const data = [];
      for (let i = 0; i < 4; i  ) {
        const image = await axios.get(
          `${api}/${Math.round(Math.random() * 1000)}`
        );
        const buffer = new Buffer(image.data);
        data.push(buffer.toString("base64"));
      }
      setAvatars(data);
      setIsLoading(false);
    };

    loadData();
  }, []);
  • Related