0

SOLVED: useEffect runs twice, when component did mount (then data.length is 0 because of scope), and when data is loaded

I have this component that receives data and then runs a setInterval, but the data.length is still 0. It seems that it is not updated. How do I fix this?

import "./App.css";
import { useEffect, useState } from "react";
import Slide from "./components/Slide";

function QuoteSlider({ data }) {
  const [currentItem, setCurrentItem] = useState({ value: "Loading" });
  useEffect(() => {
    setInterval(() => {
      randomItem();
    }, 4000);
  }, [data]);
  function randomItem() {
    console.log("data.length is " + data.length);
    const randomNumber = Math.floor(Math.random() * data.length);
    const newItem = data[randomNumber];
    setCurrentItem(newItem);
  }
  return <div>{currentItem?.value}</div>;
}

export default QuoteSlider;

And in the parent:

<QuoteSlider data={[{someData: 'here'},{someData: 'one more']}/>
Oba Api
  • 231
  • 1
  • 3
  • 10
  • 1
    Please provide a [mcve]. Also, what problem are you trying to solve with this code? Your question feels like an XY problem. – Code-Apprentice Feb 18 '22 at 21:38
  • I've updated it – Oba Api Feb 18 '22 at 21:41
  • 2
    I suggest you read about closures. – Code-Apprentice Feb 18 '22 at 21:45
  • 1
    You may want to not prematurely destructure props. Also see https://stackoverflow.com/questions/53024496/state-not-updating-when-using-react-state-hook-within-setinterval – Estus Flask Feb 18 '22 at 21:49
  • I strongly suggest you read this [article](https://overreacted.io/making-setinterval-declarative-with-react-hooks/) – Ahmed Tarek Feb 18 '22 at 22:24
  • The problem was that useEffect runs twice: when component did mount, and when data is loaded. This makes the setInterval run twice, which created the data having length 0 alternating with data as it should be. – Oba Api Feb 19 '22 at 05:41

0 Answers0