I am adding items to the wishlist and once it is added I am trying to re-render the Heart icon to have a number on it to indicate that the Item has been added to the wishlist. What I want to achieve is similar to Twitter's like button, when someone likes the post the number of likes increases immediately. So, in my case when someone likes (wishlists) the product it will increase the number on top of Heart icon. I am using local storage to get the items that are added to the wishlist, and I can re-render the Wishlist component when a new Item is added inside the effect but it makes the component to re-render infinitely which is giving me a warning of Warning: Maximum update depth exceeded
Here is my effect;
const [wishlist, setWishlist] = React.useState([]);
React.useEffect(() => {
if (typeof window !== "undefined") {
const wishlistStorage =
localStorage.getItem("wishlist") === null
? []
: [...JSON.parse(localStorage.getItem("wishlist"))];
if (wishlistStorage.length > 0) {
setWishlist(wishlistStorage);
}
}
}, [wishlist]);
If I remove the wishlist from dependancy array, I need to refresh the page to see the correct number of items. What am I doing wrong here and what would be the best way to approach this. Thank you!
just remove the wishlist from the dependencies
React.useEffect(() => {
if (typeof window !== "undefined") {
const wishlistStorage =
localStorage.getItem("wishlist") === null
? []
: [...JSON.parse(localStorage.getItem("wishlist"))];
if (wishlistStorage.length > 0) {
setWishlist(wishlistStorage);
}
}
}, []);
Here you have add wishlist in dependency array of useEffect and in that you have added condition if (wishlistStorage.length > 0) { setWishlist(wishlistStorage); } , because setting again the wishlist it will cause re-render and again useEffect will be triggered.
If I understand correctly, and you need this only for the initial render, then you can simply remove wishlist from the dependency array.
const [wishlist, setWishlist] = React.useState([]);
React.useEffect(() => {
if (typeof window !== "undefined") {
const wishlistStorage =
localStorage.getItem("wishlist") === null
? []
: [...JSON.parse(localStorage.getItem("wishlist"))];
if (wishlistStorage.length > 0) {
setWishlist(wishlistStorage);
}
}
}, []);