Refactor: Follow and Follow Categories in the same page

This commit is contained in:
EvanLin3141
2025-03-03 13:31:37 +00:00
parent 653fbb7352
commit 2494e40ffd
4 changed files with 30 additions and 188 deletions

View File

@@ -15,7 +15,6 @@ import DashboardPage from "./pages/DashboardPage";
import { Brightness } from "./context/BrightnessContext"; import { Brightness } from "./context/BrightnessContext";
import LoadingScreen from "./components/Layout/LoadingScreen"; import LoadingScreen from "./components/Layout/LoadingScreen";
import Following from "./pages/Following"; import Following from "./pages/Following";
import FollowedCategories from "./pages/FollowedCategories";
function App() { function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false); const [isLoggedIn, setIsLoggedIn] = useState(false);

View File

@@ -1,101 +0,0 @@
import React, { useEffect, useState } from "react";
import { useAuth } from "../context/AuthContext";
import { useNavigate } from "react-router-dom";
import DynamicPageContent from "../components/Layout/DynamicPageContent";
import { useFollow } from "../hooks/useFollow";
import { useAuthModal } from "../hooks/useAuthModal";
import FollowUserButton from "../components/Input/FollowUserButton";
interface Streamer {
user_id: number;
username: string;
}
interface FollowingStreamerProps {
extraClasses?: string;
}
const FollowUsers: React.FC<FollowingStreamerProps> = ({ extraClasses = "" }) => {
const navigate = useNavigate();
const { isLoggedIn } = useAuth();
const [followedStreamers, setFollowedStreamers] = useState<Streamer[]>([]);
const [followingStatus, setFollowingStatus] = useState<{ [key: number]: boolean }>({}); // Store follow status for each streamer
const { isFollowing, checkFollowStatus, followUser, unfollowUser } =
useFollow();
useEffect(() => {
const fetchFollowedStreamers = async () => {
try {
const response = await fetch("/api/user/following");
if (!response.ok) throw new Error("Failed to fetch followed streamers");
const data = await response.json();
setFollowedStreamers(data);
const updatedStatus: { [key: number]: boolean } = {};
for (const streamer of data || []) {
const status = await checkFollowStatus(streamer.username);
updatedStatus[streamer.user_id] = Boolean(status);
}
setFollowingStatus(updatedStatus);
console.log("Fetched Follow Status:", updatedStatus); // Log the status
} catch (error) {
console.error("Error fetching followed streamers:", error);
}
};
if (isLoggedIn) {
fetchFollowedStreamers();
}
}, [isLoggedIn]);
const handleFollowToggle = async (userId: number) => {
const isCurrentlyFollowing = followingStatus[userId];
if (isCurrentlyFollowing) {
await unfollowUser(userId);
} else {
await followUser(userId);
}
// Update local state for this specific streamer
setFollowingStatus((prev) => ({
...prev,
[userId]: !isCurrentlyFollowing, // Toggle based on previous state
}));
};
return (
<DynamicPageContent>
<div
id="sidebar"
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide transition-all duration-500 ease-in-out ${extraClasses}`}
>
<div
id="followed-users"
className={`grid grid-cols-2 gap-4 p-4 w-full`}>
{followedStreamers.map((streamer: any) => (
<div
key={`streamer-${streamer.username}`}
className="cursor-pointer bg-black w-full py-2 border border-[--text-color] rounded-lg text-white hover:text-purple-500 font-bold transition-colors"
/*onClick={() => navigate(`/user/${streamer.username}`)}*/
>
{streamer.username}
<FollowUserButton
user={{
user_id: streamer.user_id,
username: streamer.username,
isFollowing: followingStatus[streamer.user_id] || true,
}}
/>
</div>
))}
</div>
</div>
</DynamicPageContent>
);
};
export default FollowUsers;

View File

@@ -1,84 +0,0 @@
import React, { useState, useEffect, useRef } from "react";
import { useAuth } from "../context/AuthContext";
import { useNavigate, useParams } from "react-router-dom";
import DynamicPageContent from "../components/Layout/DynamicPageContent";
import { useCategoryFollow } from "../hooks/useCategoryFollow";
import FollowButton from "../components/Input/FollowButton";
import { useAuthModal } from "../hooks/useAuthModal";
interface Category {
isFollowing: boolean;
category_id: number;
category_name: string;
}
interface FollowedCategoryProps {
extraClasses?: string;
}
const FollowedCategories: React.FC<FollowedCategoryProps> = ({ extraClasses = "" }) => {
const navigate = useNavigate();
const { username, isLoggedIn } = useAuth();
const [followedCategories, setFollowedCategories] = useState<Category[]>([]);
const { categoryName } = useParams<{ categoryName: string }>();
const { checkCategoryFollowStatus, followCategory, unfollowCategory } = useCategoryFollow();
useEffect(() => {
if (categoryName) checkCategoryFollowStatus(categoryName);
}, [categoryName]);
useEffect(() => {
if (!isLoggedIn) return;
const fetchFollowedCategories = async () => {
try {
const response = await fetch("/api/categories/your_categories");
if (!response.ok) throw new Error("Failed to fetch followed categories");
const data = await response.json();
setFollowedCategories(data);
} catch (error) {
console.error("Error fetching followed categories:", error);
}
};
fetchFollowedCategories();
}, [isLoggedIn]);
return (
<DynamicPageContent>
<div
id="sidebar"
className={`top-0 left-0 w-screen h-screen overflow-x-hidden flex flex-col bg-[var(--sideBar-bg)] text-[var(--sideBar-text)] text-center overflow-y-auto scrollbar-hide transition-all duration-500 ease-in-out ${extraClasses}`}
>
{/* Followed Categories */}
<div id="categories-followed" className="grid grid-cols-4 gap-4 p-4 w-full">
{followedCategories.map((category) => {
return (
<div
key={category.category_id}
className="relative flex flex-col items-center justify-center border border-[--text-color] rounded-lg overflow-hidden hover:shadow-lg transition-all"
onClick={() => navigate(`/category/${category.category_name}`)}
>
<FollowButton category={category}/>
<img
src={`/images/category_thumbnails/${category.category_name.toLowerCase().replace(/ /g, "_")}.webp`}
alt={category.category_name}
className="w-full h-28 object-cover"
/>
<div className="absolute bottom-2 bg-black bg-opacity-60 w-full text-center text-white py-1">
{category.category_name}
</div>
</div>
);
})}
</div>
</div>
</DynamicPageContent>
);
};
export default FollowedCategories;

View File

@@ -4,6 +4,7 @@ import { useLocation, useNavigate } from "react-router-dom";
import DynamicPageContent from "../components/Layout/DynamicPageContent"; import DynamicPageContent from "../components/Layout/DynamicPageContent";
import { useFollow } from "../hooks/useFollow"; import { useFollow } from "../hooks/useFollow";
import FollowUserButton from "../components/Input/FollowUserButton"; import FollowUserButton from "../components/Input/FollowUserButton";
import FollowButton from "../components/Input/FollowButton";
interface Streamer { interface Streamer {
user_id: number; user_id: number;
@@ -11,6 +12,7 @@ interface Streamer {
} }
interface Category { interface Category {
isFollowing: boolean;
category_id: number; category_id: number;
category_name: string; category_name: string;
} }
@@ -30,7 +32,7 @@ const Following: React.FC<FollowingProps> = ({ extraClasses = "" }) => {
const location = useLocation(); const location = useLocation();
const queryParams = new URLSearchParams(location.search); const queryParams = new URLSearchParams(location.search);
const initialTab = queryParams.get("tab") === "streamers" ? "streamers" : "categories"; const initialTab = queryParams.get("tab") === "streamers" ? "categories" : "categories";
const [activeTab, setActiveTab] = useState<"categories" | "streamers">(initialTab); const [activeTab, setActiveTab] = useState<"categories" | "streamers">(initialTab);
//const [followingStatus, setFollowingStatus] = useState<Record<number, boolean>>({}); //const [followingStatus, setFollowingStatus] = useState<Record<number, boolean>>({});
@@ -103,6 +105,32 @@ const Following: React.FC<FollowingProps> = ({ extraClasses = "" }) => {
))} ))}
</div> </div>
)} )}
{activeTab === "categories" && (
<div id="categories-followed" className="grid grid-cols-4 gap-4 p-4 w-full">
{followedCategories.map((category) => {
return (
<div
key={category.category_id}
className="relative flex flex-col items-center justify-center border border-[--text-color] rounded-lg overflow-hidden hover:shadow-lg transition-all"
onClick={() => navigate(`/category/${category.category_name}`)}
>
<FollowButton category={category} />
<img
src={`/images/category_thumbnails/${category.category_name.toLowerCase().replace(/ /g, "_")}.webp`}
alt={category.category_name}
className="w-full h-28 object-cover"
/>
<div className="absolute bottom-2 bg-black bg-opacity-60 w-full text-center text-white py-1">
{category.category_name}
</div>
</div>
);
})}
</div>
)};
</div> </div>