Skip to content

Commit

Permalink
Implement SSR for website
Browse files Browse the repository at this point in the history
  • Loading branch information
cp-dharti-r committed May 15, 2024
1 parent 33eb97a commit 557cacc
Show file tree
Hide file tree
Showing 9 changed files with 500 additions and 519 deletions.
42 changes: 7 additions & 35 deletions website/components/FoodCategory/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,41 +17,13 @@ import CategorySwiperSkeleton from "../SkeletonPlaceholders/CategorySwiper";
import { useAppDispatch, useAppSelector } from "@/store/store";
import { setCategoriesState } from "@/store/home/slice";

const FoodCategory = () => {
const dispatch = useAppDispatch();
const foodDataState = useAppSelector((state) => state.home.categories);

const [isFoodLoading, setIsFoodLoading] = useState(true);
const [foodData, setFoodData] = useState<any | null>([]);

useEffect(() => {
const fetchCategories = async () => {
try {
const { data, error } = await supabase
.from("categories")
.select("*")
.eq("restaurant_id", 0)
.order("id", { ascending: true });

if (error) throw error;

dispatch(setCategoriesState(data));
setFoodData(data);
} catch (error) {
console.error("Error fetching data:", error);
} finally {
setIsFoodLoading(false);
}
};

if (foodDataState.length == 0) {
fetchCategories();
} else {
setFoodData(foodDataState);
setIsFoodLoading(false);
}
}, [dispatch, foodDataState, foodDataState.length]);

const FoodCategory = ({
foodData,
isFoodLoading,
}: {
foodData: any;
isFoodLoading: boolean;
}) => {
return (
<>
<section className="py-16 md:py-20 lg:py-28">
Expand Down
56 changes: 2 additions & 54 deletions website/components/ItemCard/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,61 +10,9 @@ import { InView } from "react-intersection-observer";
import { useAppDispatch, useAppSelector } from "@/store/store";
import { setFoodItemsState } from "@/store/home/slice";

const ItemCard = () => {
const dispatch = useAppDispatch();
const ItemCard = ({ itemData }: { itemData: any }) => {
const isPageReset = useAppSelector((state) => state.app.isPageReset);
const itemDataState = useAppSelector((state) => state.home.foodItems);
const [itemData, setMostBrowsedItemData] = useState<any | null>([]);

useEffect(() => {
const fetchData = async () => {
try {
// Fetch menu IDs associated with public restaurants
const { data: menusData, error: menuError } = await supabase
.from("menus")
.select("id, restaurants(id)")
.eq("restaurants.is_public", true)
.not("restaurants", "is", null);

if (menuError) throw menuError;

// Extract menu IDs
const menuIds = menusData.map((menu) => menu.id);

// Fetch dishes associated with the obtained menu IDs
const { data: dishesData, error: dishesError } = await supabase
.from("dishes")
.select("*, menus(id, restaurants(id, name, address))")
.in("menu_id", menuIds)
.order("id", { ascending: true })
.limit(9);

if (dishesError) throw dishesError;

const restaurant = await Promise.all(
dishesData.map(async (dish) => {
return {
...dish,
image: dish.images ? dish.images[0] : "",
rating: 4.2,
};
})
);

dispatch(setFoodItemsState(restaurant));
setMostBrowsedItemData(restaurant);
} catch (error) {
console.error("Error fetching data:", error);
}
};

if (itemDataState.length == 0) {
fetchData();
} else {
setMostBrowsedItemData(itemDataState);
}
}, [dispatch, itemDataState, itemDataState.length]);


return (
<section className="bg-primary bg-opacity-10 py-16 md:py-20 lg:py-28">
<div className="container animated-fade">
Expand Down
31 changes: 1 addition & 30 deletions website/components/YouMayLike/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,8 @@ import "swiper/css/effect-fade";
import { useAppDispatch, useAppSelector } from "@/store/store";
import { setRestaurantsState } from "@/store/home/slice";

const YouMayLike = () => {
const dispatch = useAppDispatch();
const YouMayLike = ({ restaurants }: { restaurants: any }) => {
const isPageReset = useAppSelector((state) => state.app.isPageReset);
const restaurantsState = useAppSelector((state) => state.home.restaurants);
const [restaurants, setRestaurantsData] = useState<any | null>([]);

useEffect(() => {
const fetchData = async () => {
try {
const { data, error } = await supabase
.from("restaurants")
.select("*")
.eq("is_public", true)
.order("id", { ascending: true })
.limit(4);

if (error) return error;

dispatch(setRestaurantsState(data));
setRestaurantsData(data);
} catch (error) {
console.error("Error while fetching restaurants data: ", error);
}
};

if (restaurantsState.length == 0) {
fetchData();
} else {
setRestaurantsData(restaurantsState);
}
}, [dispatch, restaurantsState, restaurantsState.length]);

return (
<>
Expand Down
2 changes: 1 addition & 1 deletion website/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
// reactStrictMode: true,
reactStrictMode: true,
images: {
unoptimized: true,
domains: ["rftxzccfellupeepddjl.supabase.co"],
Expand Down
219 changes: 103 additions & 116 deletions website/pages/category/[category].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,123 +13,16 @@ import { useAppDispatch, useAppSelector } from "@/store/store";
import { setCategoryState, setRestaurantsState } from "@/store/category/slice";
import withScrollRestoration from "@/components/withScrollRestoration";

const Category = () => {
const router = useRouter();
const { category } = router.query;
const suffix = category?.toString().substring(category?.lastIndexOf("-") + 1);

const dispatch = useAppDispatch();
const Category = ({
categoryData,
restaurantsData,
isRestaurantsLoading,
}: {
categoryData: CategoryData;
restaurantsData: RestaurantData[];
isRestaurantsLoading: boolean;
}) => {
const isPageReset = useAppSelector((state) => state.app.isPageReset);
const categoriesState = useAppSelector((state) => state.category.categories);
const categoryRestaurantsState = useAppSelector(
(state) => state.category.restaurants
);

const [categoryData, setCategoryData] = useState<CategoryData | null>(null);
const [restaurantsData, setCategoriesRestaurantsData] = useState<
RestaurantData[]
>([]);

const [isRestaurantsLoading, setIsRestaurantsLoading] = useState(true);

useEffect(() => {
const fetchCategoryData = async () => {
if (
categoryRestaurantsState.some((item: any) => item.id === atob(suffix!))
) {
return;
}

if (suffix) {
try {
const { data, error } = await supabase
.from("categories")
.select("*")
.eq("id", atob(suffix!))
.single();

if (error) throw error;

dispatch(setCategoryState({ id: atob(suffix!), data: data }));
setCategoryData(data);

const { data: categoryDatas, error: categoriesError } = await supabase
.from("categories")
.select("id, name, description, restaurant_id, image")
.neq("restaurant_id", 0)
.order("id", { ascending: false })
.contains("tags", [data.name.toLowerCase()]);

if (categoriesError) throw categoriesError;

const restaurant = await Promise.all(
categoryDatas.map(async (category) => {
const { data: restaurantData, error: restaurantError } =
await supabase
.from("restaurants")
.select("id, name, address")
.eq("id", category.restaurant_id)
.eq("is_public", true)
.single();

if (restaurantError)
console.error(
"Error fetching restaurant details:",
restaurantError
);

if (restaurantData) {
return {
...restaurantData,
category: category,
rating: 0,
reviews: 0,
};
} else {
return {
id: 0,
name: "",
address: "",
category: category,
rating: 0,
reviews: 0,
};
}
})
);

dispatch(
setRestaurantsState({ id: atob(suffix!), data: restaurant })
);

setCategoriesRestaurantsData(restaurant);
} catch (error) {
console.error("Error fetching category data:", error);
} finally {
setIsRestaurantsLoading(false);
}
}
};

if (categoriesState.length > 0) {
if (categoriesState.some((item: any) => item.id == atob(suffix!))) {
setCategoryData(
categoriesState.filter((item: any) => item.id === atob(suffix!))[0]
.data
);
setCategoriesRestaurantsData(
categoryRestaurantsState.filter(
(item: any) => item.id === atob(suffix!)
)[0].data
);
setIsRestaurantsLoading(false);
} else {
fetchCategoryData();
}
} else if (categoriesState.length == 0) {
fetchCategoryData();
}
}, [dispatch, suffix]);

return (
<>
Expand Down Expand Up @@ -171,4 +64,98 @@ const Category = () => {
);
};

interface FetchCategoryDataResult {
categoryData: CategoryData;
restaurantsData: RestaurantData[];
}

export async function getServerSideProps(context: any) {
const { params } = context;
const { category } = params;
const suffix = category?.toString().substring(category?.lastIndexOf("-") + 1);

let isRestaurantsLoading = true;

const fetchCategoryData = async (): Promise<
FetchCategoryDataResult | undefined
> => {
if (suffix) {
try {
const { data: categoryData, error } = await supabase
.from("categories")
.select("*")
.eq("id", atob(suffix!))
.single();

if (error) throw error;

const { data: categoryDatas, error: categoriesError } = await supabase
.from("categories")
.select("id, name, description, restaurant_id, image")
.neq("restaurant_id", 0)
.order("id", { ascending: false })
.contains("tags", [categoryData.name.toLowerCase()]);

if (categoriesError) throw categoriesError;

const restaurantsData = await Promise.all(
categoryDatas.map(async (category) => {
const { data: restaurantData, error: restaurantError } =
await supabase
.from("restaurants")
.select("id, name, address")
.eq("id", category.restaurant_id)
.eq("is_public", true)
.single();

if (restaurantError)
console.error(
"Error fetching restaurant details:",
restaurantError
);

if (restaurantData) {
return {
...restaurantData,
category: category,
rating: 0,
reviews: 0,
};
} else {
return {
id: 0,
name: "",
address: "",
category: category,
rating: 0,
reviews: 0,
};
}
})
);

return { categoryData, restaurantsData };
} catch (error) {
console.error("Error fetching category data:", error);
}
}
};

const {
categoryData,
restaurantsData,
}: { categoryData: CategoryData; restaurantsData: RestaurantData[] } =
(await fetchCategoryData())!;

isRestaurantsLoading = false;

return {
props: {
categoryData,
restaurantsData,
isRestaurantsLoading,
},
};
}

export default withScrollRestoration(Category);
Loading

0 comments on commit 557cacc

Please sign in to comment.