import { updateRestaurant, clearCart } from "features/order/orderSlice"; import { useEffect, useRef } from "react"; import { useAppDispatch } from "redux/hooks"; import { RestaurantDetails } from "utils/types/appTypes"; /** * Custom hook to automatically load restaurant into Redux store * when restaurant data is available * Clears the cart when the restaurant (subdomain) changes */ export const useRestaurant = (restaurant: RestaurantDetails | undefined) => { const dispatch = useAppDispatch(); const previousRestaurantIdRef = useRef(null); useEffect(() => { if (restaurant) { const currentRestaurantId = restaurant.restautantId; // Check if restaurant has changed if ( previousRestaurantIdRef.current !== null && previousRestaurantIdRef.current !== currentRestaurantId ) { // Restaurant changed, clear the cart dispatch(clearCart()); } // Update the previous restaurant ID previousRestaurantIdRef.current = currentRestaurantId; // Update restaurant in store dispatch(updateRestaurant(restaurant)); } }, [restaurant, dispatch]); };