I'm using a custom hook to fetch data from api , and my dependency array only contain my setStates functions but still it keeps re re rendering.
From what I learned from useEffect hook is that it only re-renders when a state in the dependency array has changed and in that case I'm not depending on any state here is my custom hook.
This hook fetches cart data of current user and it works fine to this point, but I only have references to the cart item inside the cart object. So I did another fetch, the problem arises from here, when I fetch the items they re-render infinitely.
useEffect(() => {
console.log('checking cart info');
if (getCartCookie()) {
console.log('cart exists');
if (!auth) {
dispatch(setLoading(false));
return;
}
}
let mounted = false;
const getCart = async () => {
if (!mounted) {
//if authenticated , get cart if not found create
if (auth) {
if (getCartCookie()) removeCookie('cart', { path: '/' });
console.log('Fetched User : ', user._id);
const { cart, err } = await getUserCart(user._id, token);
console.log('Fetched User cart : ', cart);
if (err) await createCart();
else {
const arr = [];
for (let i of cart?.items) {
console.log('fetcing items......');
const { item } = await getItem(i.item);
console.log('item : ', item);
if (!item) continue;
arr.push(item);
}
dispatch(setItems(arr));
setCookie('cart', cart, { path: '/' });
removeCookie('cartErr', { path: '/' });
dispatch(setCart(cart));
dispatch(setCart_c(cart.items.length));
removeCookie('cartErr', { path: '/' });
console.log('cart state : ', cart);
}
} else {
await createCart();
removeCookie('cartErr', { path: '/' });
}
}
dispatch(setLoading(false));
};
getCart();
return () => {
mounted = true;
};
}, [dispatch , setCart , setCart_c , setCookie , setItems]);