All files / src/components/features/cart WishlistInitializer.tsx

0% Statements 0/34
100% Branches 0/0
0% Functions 0/1
0% Lines 0/34

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35                                                                     
'use client';

import { useEffect, useRef } from 'react';
import { useSession } from 'next-auth/react';
import { useDispatch } from 'react-redux';
import { fetchWishlist } from '@/redux/features/wishlistSlice';
import { AppDispatch, useAppSelector } from '@/redux/store';

/**
 * WishlistInitializer
 *
 * Initializes the wishlist on app load by fetching from the API.
 * Re-fetches when authentication status changes.
 */
export function WishlistInitializer() {
  const dispatch = useDispatch<AppDispatch>();
  const { status } = useSession();
  const isLoaded = useAppSelector((state) => state.wishlistReducer.isLoaded);
  const previousStatus = useRef<string | null>(null);

  useEffect(() => {
    // Wait for session to be determined
    if (status === 'loading') return;

    // Fetch on first load or when auth status changes
    if (!isLoaded || previousStatus.current !== status) {
      previousStatus.current = status;
      dispatch(fetchWishlist());
    }
  }, [dispatch, status, isLoaded]);

  // This component doesn't render anything
  return null;
}