36 lines
1.2 KiB
TypeScript
36 lines
1.2 KiB
TypeScript
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<string | null>(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]);
|
|
};
|