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>
);
}
CodePudding user response:
Use effect called when Carousels changed and Corausels 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>
);
}
CodePudding user response:
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