Infinite fetching bug from Firestore

I am implementing this custom hook for a cart where basically fetches productIds, and variants from async storage, then fetch all the information of the products from Firestore. The logic then syncs the fetched data and displays it. I also implemented Firestore’s real-time capabilities. It somehow works as it should however, based on the logs I put, the fetching seems to be infinite (based on the logs).

Here is the custom hook:

import { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import firestore from '@react-native-firebase/firestore';
import { useDebounce } from 'use-debounce';

const CART_KEY = 'CART_KEY';
const BATCH_SIZE = 5;

const useCartProducts = () => {
  const [cart, setCart] = useState([]);
  const [loading, setLoading] = useState(true);
  const [productDetails, setProductDetails] = useState({});
  const [lastVisible, setLastVisible] = useState(null);
  const [isFetchingMore, setIsFetchingMore] = useState(false);
  const initialFetch = useRef(true);
  const updatingCart = useRef(false);
  const [debouncedCart] = useDebounce(cart, 500);

  // Fetch cart from AsyncStorage once on mount
  useEffect(() => {
    const fetchCart = async () => {
      try {
        const storedCart = await AsyncStorage.getItem(CART_KEY);
        const parsedCart = storedCart ? JSON.parse(storedCart) : [];
        console.log('Cart Items From AsyncStorage:', parsedCart);
        setCart(parsedCart);
      } catch (error) {
        console.error('Failed to fetch cart:', error);
      } finally {
        setLoading(false);
      }
    };
    fetchCart();
  }, []);

  // Fetch product details in batches (lazy loading)
  const fetchProductDetails = useCallback(async () => {
    console.log('fetchProductDetails called');
    if (cart.length === 0 || isFetchingMore) {
      console.log('No products to fetch or already fetching more');
      return;
    }

    const productIds = [...new Set(cart.map(item => item.productId))];
    if (productIds.length === 0) {
      console.log('No product IDs found in cart');
      return;
    }

    setIsFetchingMore(true);
    console.log('Fetching product details for IDs:', productIds);

    let query = firestore()
      .collection('products')
      .where(firestore.FieldPath.documentId(), 'in', productIds)
      .limit(BATCH_SIZE);

    if (lastVisible) {
      query = query.startAfter(lastVisible);
    }

    try {
      const querySnapshot = await query.get();
      if (!querySnapshot.empty) {
        const details = {};
        querySnapshot.forEach(doc => {
          details[doc.id] = doc.data();
        });

        setProductDetails(prevDetails => ({ ...prevDetails, ...details }));
        setLastVisible(querySnapshot.docs[querySnapshot.docs.length - 1]);
        console.log('Fetched product details:', details);
      } else {
        console.log('No more products to fetch');
      }
    } catch (error) {
      console.error('Error fetching product details:', error);
    } finally {
      setIsFetchingMore(false);
    }
  }, [cart, lastVisible, isFetchingMore]);

  // Fetch initial product details when cart changes
  useEffect(() => {
    if (initialFetch.current) {
      console.log('Initial cart fetch, skipping fetchProductDetails');
      initialFetch.current = false;
    } else {
      fetchProductDetails();
    }
  }, [debouncedCart, fetchProductDetails]);

  // Sync cart items with product details
  useEffect(() => {
    console.log('Product details changed:', productDetails);
    if (Object.keys(productDetails).length === 0) return;

    setCart(prevCart =>
      prevCart.map(item => ({
        ...item,
        data: productDetails[item.productId],
      }))
    );
  }, [productDetails]);

  // Real-time updates for cart products
  useEffect(() => {
    console.log('Setting up real-time updates for cart products');
    const productIds = [...new Set(cart.map(item => item.productId))];
    if (productIds.length === 0) return;

    const unsubscribe = firestore()
      .collection('products')
      .where(firestore.FieldPath.documentId(), 'in', productIds)
      .onSnapshot(snapshot => {
        if (updatingCart.current) return;
        const changes = {};
        snapshot.forEach(doc => {
          changes[doc.id] = doc.data();
        });
        console.log('Real-time changes:', changes);
        setProductDetails(prevDetails => ({ ...prevDetails, ...changes }));
      });

    return () => {
      console.log('Cleaning up real-time updates');
      unsubscribe();
    };
  }, [cart, updatingCart]);

  const updateQuantity = useCallback(async (productId, variant, quantity) => {
    console.log('updateQuantity called:', productId, variant, quantity);
    if (quantity <= 0) return;

    updatingCart.current = true;
    setCart(prevCart => {
      const updatedCart = prevCart.map(item =>
        item.productId === productId && item.variant[0] === variant[0]
          ? { ...item, quantity }
          : item
      );
      console.log('Quantity changes:', updatedCart);
      AsyncStorage.setItem(CART_KEY, JSON.stringify(updatedCart));
      return updatedCart;
    });
    updatingCart.current = false;
  }, []);

  const removeProduct = useCallback(async (productId, variant) => {
    console.log('removeProduct called:', productId, variant);
    updatingCart.current = true;
    setCart(prevCart => {
      const updatedCart = prevCart.filter(
        item => !(item.productId === productId && item.variant[0] === variant[0])
      );
      AsyncStorage.setItem(CART_KEY, JSON.stringify(updatedCart));
      return updatedCart;
    });
    updatingCart.current = false;
  }, []);

  const totalPrice = useMemo(
    () => cart.reduce(
      (acc, item) => acc + item.quantity * parseFloat(item.variant[1].price),
      0
    ),
    [cart]
  );

  console.log('Total price:', totalPrice);

  return {
    cart,
    loading,
    updateQuantity,
    removeProduct,
    totalPrice,
    loadMoreProducts: fetchProductDetails,
  };
};

export default useCartProducts;

New contributor

Josh Lsc is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật