2

I'm trying to fetch some data from the API, but doesn't matter which dependencies I use, useEffect still keeps making an infinite loop, is there something wrong in the code or why it keeps doing that?

function HomePage() {
    const [Carousels, setCarousels] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const getCarousels = async () => {
            setLoading(true);
            const genres = ["BestRated", "Newest"];
            for (const genre of genres) {
                try {
                    const res = await axios.get(`http://localhost:4000/api/carousels/` + genre);
                    console.log(res.data);
                    setCarousels([...Carousels, res.data]);
                } catch (err) {
                    console.log(err);
                }
            }
            setLoading(false);
        }
        getCarousels();
    }, [Carousels]);
    return (
        <div className='Home'>
            <NavBar />
            <HeroCard />
            {!loading && Carousels.map((carousel) => (
                <Carousel key={carousel._id} carousel={carousel} />
            ))}
            <Footer />
        </div>
    );
}

2 Answers 2

2

Use effect called when Carousels changed and Carousels changed inside useEffect.

Use set state with callback

function HomePage() {
    const [Carousels, setCarousels] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        const getCarousels = async () => {
            setLoading(true);
            const genres = ["BestRated", "Newest"];
            for (const genre of genres) {
                try {
                    const res = await axios.get(`http://localhost:4000/api/carousels/` + genre);
                    console.log(res.data);
                    setCarousels(carouselsPrev => [...carouselsPrev, res.data]);
                } catch (err) {
                    console.log(err);
                }
            }
            setLoading(false);
        }
        getCarousels();
    }, []);
    return (
        <div className='Home'>
            <NavBar />
            <HeroCard />
            {!loading && Carousels.map((carousel) => (
                <Carousel key={carousel._id} carousel={carousel} />
            ))}
            <Footer />
        </div>
    );
}
Sign up to request clarification or add additional context in comments.

6 Comments

I changed the setCarousels, and it stopped the infinite loop, but I don't know why, Carousels aren't updated properly, it doesn't get the response from res.data
@TrifIonut Can you log res output?
Yes, the res works just fine, but somehow it isn't added in Carousels
@TrifIonut Can you show me the output console.log(res)
This is shown from log(res.data) Array(1) 0: {_id: '627d6e54f1a6fc3a220b9ffa', title: 'Best Rated Movies', genre: 'BestRated', content: Array(10), createdAt: '2022-05-12T20:30:12.978Z', …} length: 1 [[Prototype]]: Array(0)
|
0

useEffect in your code updates Carousels each run. It sees the updated value and runs again. You could fix it various ways, the easiest would be to add [fetched, setFetched] = useState(false); and use it in your useEffect to check before fetching from the API

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.