useEffect infinite loop when fetching from the api - reactjs

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>
);
}

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>
);
}

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

Related

How to update the useState in the promise function of the react js

As I want to update the products array loaded from the API in the useState but as I update it shows me the error in the console but it works I want to solve that error
const [loading, setloading] = useState(true);
const [productslist, setproductslist] = useState([]);
const currentSlug = useParams();
const BrandWiseProduct = () => {
setloading(true);
api.get(`brand/${currentSlug.slug}/`).then((response) => {
setproductslist(response.data);
});
setloading(false);
};
const ProductCardRender = productslist.map((product, index) => {
return (
<ProductCard
name={product.name}
price={product.price}
key={product.id}
slug={product.slug}
image={product.card_banner}
/>
);
});
This is the code and here is the screenshot of the error
If there is any better way then please suggest to me you can share any article or blog post.
Thanks in Advance
Actually, might be able to do it like this:
import { useEffect, Suspense } from "react";
const ProductCardRender = () => {
const [loading, setloading] = useState(true);
const [productslist, setproductslist] = useState([]);
const currentSlug = useParams();
useEffect(() => {
const BrandWiseProduct = () => {
setloading(true);
api.get(`brand/${currentSlug.slug}/`).then((response) => {
setproductslist(response.data);
});
setloading(false);
};
BrandWiseProduct();
}, []);
return (
<Suspense fallback={<h1>Loading...</h1>}>
{productslist.map((product, index) => (
<ProductCard
name={product.name}
price={product.price}
key={product.id}
slug={product.slug}
image={product.card_banner}
/>
))}
</Suspense>
);
};

stop/prevent scrolling to top on re render in React using Hooks (need to implement infinite scrolling)

I am trying to setup infinite scrolling using React Hooks, I am getting the data correctly from the node backend (3 dataset per request), and when I scroll new data is also added correctly in the array (in the loadedPlaces state), but the page is going back to top on re render, I need to prevent this behavior. How do I prevent this, and below is my code
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [page, setPage] = useState(1);
const [loadedPlaces, setLoadedPlaces] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const getPlaces = async () => {
try {
setIsLoading(true);
const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
const responseData = await fetch(url);
const data = await responseData.json();
console.log(data);
setLoadedPlaces((prev) => [...prev, ...data.places]);
setIsLoading(false);
} catch (error) {}
};
getPlaces();
}, [page]);
window.onscroll = function (e) {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
return (
<div className='App'>
<h1>Infinite Scroll</h1>
{!isLoading &&
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
</div>
);
}
export default App;
Any help is highly appreciated
This is happening because whenever you scroll you are calling
window.onscroll = function (e) {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
And it's changing the page count and that changed page count leads to again run the
useEffect(() => {
const getPlaces = async () => {
try {
setIsLoading(true);
const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
const responseData = await fetch(url);
const data = await responseData.json();
console.log(data);
setLoadedPlaces((prev) => [...prev, ...data.places]);
setIsLoading(false);
} catch (error) {}
};
getPlaces();
}, [page]);
and in that function, you are doing setIsLoading(true) so that it is again rendering this because of
{!isLoading && <-----
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
And that leads you to the top of the page
You can try this approach:
import React, { useEffect, useState } from "react";
import "./App.css";
function App() {
const [page, setPage] = useState(1);
const [loadedPlaces, setLoadedPlaces] = useState([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const getPlaces = async () => {
try {
setIsLoading(true);
const url = `http://localhost:5000/api/places/user/${id}?page=${page}&size=3`;
const responseData = await fetch(url);
const data = await responseData.json();
console.log(data);
setLoadedPlaces((prev) => [...prev, ...data.places]);
setIsLoading(false);
} catch (error) {}
};
getPlaces();
}, [page]);
window.onscroll = function (e) {
if (
window.innerHeight + document.documentElement.scrollTop ===
document.documentElement.offsetHeight
) {
setPage(page + 1);
}
};
return (
<div className='App'>
<h1>Infinite Scroll</h1>
{
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
</div>
);
}
export default App;
You can add this.
function ScrollToBottom(){
const elementRef = useRef();
useEffect(() => elementRef.current.scrollIntoView());
return <div ref={elementRef} />;
};
And then:
return (
<div className='App'>
<h1>Infinite Scroll</h1>
{!isLoading &&
loadedPlaces.length > 0 &&
loadedPlaces.map((place, index) => (
<div key={index} className={"container"}>
<h1>{place.location.lat}</h1>
<h1>{place.location.lng}</h1>
<h1>{place.title}</h1>
<h1>{place.description}</h1>
<h1>{place.address}</h1>
<hr></hr>
</div>
))}
<ScrollToBottom />
</div>
);

Too many re-renders for component

I am trying to call a component that shows the details of a notification when the notification is clicked. However, I kept on getting an error of too many re-renders.
This is my Notifications code
This component calls the database to get the list of notifications and then sets the first notification as the default notification clicked.
const Notification = (hospital) => {
const [users, setUsers] = useState([]);
const [search, setSearch] = useState(null);
const [status, setStatus] = useState(null);
const [notifDetails, setNotification] = useState();
useEffect(async () => {
await axios
.get("/notifications")
.then((res) => {
const result = res.data;
setUsers(result);
setNotification(result[0]);
})
.catch((err) => {
console.error(err);
});
}, []);
return(
<div className="hospital-notif-container">
{filteredList(users, status, search).map((details, index) => {
for (var i = 0; i < details.receiver.length; i++) {
if (
(details.receiver[i].id === hospital.PK ||
details.receiver[i].id === "others") &&
details.sender.id !== hospital.PK
) {
return (
<div
className="hospital-notif-row"
key={index}
onClick={() => setNotification(details)}
>
<div className="hospital-notif-row">
{details.name}
</div>
</div>
);
}
}
return null;
})}
</div>
<NotificationDetails details={notifDetails} />
);
}
For NotificationDetails:
This function is triggered when a notification is clicked from Notifications. The error is said to be coming from this component.
const NotificationDetails = ({ details }) => {
const [loading, setLoading] = useState(true);
useEffect(() => {
if (Object.keys(details).length != 0) {
setLoading(false);
}
}, [details]);
if (!loading) {
return (
<>
<div className="hospital-details-container">
<h2>{details.sender.name}</h2>
</div>
</>
);
} else {return (<div>Loading</div>);}
};
What should I do to limit the re-render? Should I change the second argument of the useEffects call? Or am I missing something in my component?
I tried calling console.log from NotificationDetails and it shows that it is infinitely rendering with the data I set in axios which is result[0]. How is this happening?
Your problem should be in NotificationDetails rendering. You should write something like:
const NotificationDetails = ({ details }) => {
const [loading, setLoading] = useState(true);
useEffect(() => {
if (details.length != 0) {
setLoading(false);
}
}, [details]);
return (
<div>
{loading &&
<div className="hospital-details-container">
<div className="hospital-details-header">
<h2>{details.sender.name}</h2>
</div>
</div>
}
{!loading &&
<div>
<ReactBootStrap.Spinner animation="border" />
</div>
}
</div>
);
}
With return outside the condition statement.
EDIT
Now I noted that you have an async useEffect that is an antipattern. You should modify your useEffect in this way:
useEffect(() => {
(async () => {
await axios
.get("/notifications")
.then((res) => {
const result = res.data;
setUsers(result);
setNotification(result[0]);
})
.catch((err) => {
console.error(err);
});
})()
}, []);

I'm getting infinite loop in React useEffect and i'm totally confused

I'm working with tmdb api, I've been using react's useEffect and useContext for minor stuff and it works. I decided to use the api and it has been going into this infinite loop anytime I try to run it. I'm using axios with useEffects and useContext. Below is the component calling axios
enter image description here
function MovieList(props) {
useEffect(() => {
const getMovies = async () => { };
try {
const response = await axios.get(movieUrl, { cancelToken: source.token });
addMovies(response.data.results);
// setLoading(false)
} catch (error) {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
// handle error
throw error
}
}
getMovies();
}, []);
return (
<React.Fragment>
<div className="container-fluid pl-5">
<h2 className="white mt-4">{pageTitle}</h2>
<div className="row">
{movies.map((movie) => {
return <Movie key={movie.id} movie={movie} />;
})}
</div>
</div>
</React.Fragment>
);
}
My code goes into an infinite loop and it's driving me crazy.
And my context code is found below:
export const MovieProvider = (props) => {
const [isFav, setIsFav] = useState(false)
const [movies, setMovies] = useState([]);
const [filtered, setFilteredMovies] = useState([])
const addMovies = (res) => {
setMovies([...res]);
}
const addFavMovies = (res) => {
if(res){
setMovies([...res]);
}
}
const addFilteredMovies = (res) => {
setFilteredMovies([...filtered, res]);
}
return (
<MovieContext.Provider value={{
fav: [isFav, setIsFav],
movies, addMovies, addFavMovies,
filtered, addFilteredMovies,
}}>
{props.children}
</MovieContext.Provider>
)
}

useState(new Map()) is not working, but object does

I honestly have no idea what is going on here. I have this code, on first render it should fetch popular repos and set them to the repos state, which should cause a re-render and paint the new repos on the DOM. The reason I use Map/obj is because I'm caching the repos to avoid re-fetch.
The code doesn't work as expected, it's not setting any new state, and I can verify it in the react dev tools. For some reason if I click around on Components in the devtools, the state updates(?!), but the DOM is still not painted (stuck on Loading), which is a very strange behavior.
export default () => {
const [selectedLanguage, setSelectedLanguage] = useState('All');
const [error, setError] = useState(null);
const [repos, setRepos] = useState(() => new Map());
useEffect(() => {
if (repos.has(selectedLanguage)) return;
(async () => {
try {
const data = await fetchPopularRepos(selectedLanguage);
setRepos(repos.set(selectedLanguage, data));
} catch (err) {
console.warn('Error fetching... ', err);
setError(err.message);
}
})();
}, [selectedLanguage, repos]);
const updateLanguage = useCallback(lang => setSelectedLanguage(lang), []);
const isLoading = () => !repos.has(selectedLanguage) && !error;
return (
<>
<LanguagesNav
selected={selectedLanguage}
updateLanguage={updateLanguage}
/>
{isLoading() && <Loading text="Fetching repos" />}
{error && <p className="center-text error">{error}</p>}
{repos.has(selectedLanguage)
&& <ReposGrid repos={repos.get(selectedLanguage)} />}
</>
);
};
However, if I change up the code to use object instead of a Map, it works as expected. What am I missing here? For example, this works (using obj instead of a Map)
const Popular = () => {
const [selectedLanguage, setSelectedLanguage] = useState('All');
const [error, setError] = useState(null);
const [repos, setRepos] = useState({});
useEffect(() => {
if (repos[selectedLanguage]) return;
(async () => {
try {
const data = await fetchPopularRepos(selectedLanguage);
setRepos(prev => ({ ...prev, [selectedLanguage]: data }));
} catch (err) {
console.warn('Error fetching... ', err);
setError(err.message);
}
})();
}, [selectedLanguage, repos]);
const updateLanguage = useCallback(lang => setSelectedLanguage(lang), []);
const isLoading = () => !repos[selectedLanguage] && !error;
return (
<>
<LanguagesNav
selected={selectedLanguage}
updateLanguage={updateLanguage}
/>
{isLoading() && <Loading text="Fetching repos" />}
{error && <p className="center-text error">{error}</p>}
{repos[selectedLanguage]
&& <ReposGrid repos={repos[selectedLanguage]} />}
</>
);
};
repos.set() mutates the current instance and returns it. Since setRepos() sees the same reference, it doesn't trigger a re-render.
Instead of
setRepos(repos.set(selectedLanguage, data));
you can use:
setRepos(prev => new Map([...prev, [selectedLanguage, data]]));

Resources