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!