From f1e22594b9add8e3514c18cb2f663689ba404d3b Mon Sep 17 00:00:00 2001 From: Sosokker Date: Sat, 10 May 2025 02:56:58 +0700 Subject: [PATCH] refactor: fetch profile with react-query --- app/(tabs)/profile.tsx | 52 +++++++++++++++++++++++++++--------------- 1 file changed, 33 insertions(+), 19 deletions(-) diff --git a/app/(tabs)/profile.tsx b/app/(tabs)/profile.tsx index 7224cac..b080de9 100644 --- a/app/(tabs)/profile.tsx +++ b/app/(tabs)/profile.tsx @@ -1,6 +1,6 @@ "use client"; -import { useEffect, useState } from "react"; +import { useState } from "react"; import { ActivityIndicator, Image, @@ -23,22 +23,21 @@ export default function ProfileScreen() { const { isAuthenticated } = useAuth(); const isFocused = useIsFocused(); - const [userId, setUserId] = useState(null); - - useEffect(() => { - let ignore = false; - async function getUser() { - const { data } = await supabase.auth.getUser(); - if (!ignore) { - setUserId(data?.user?.id ?? null); - } - } - if (isAuthenticated) getUser(); - else setUserId(null); - return () => { - ignore = true; - }; - }, [isAuthenticated]); + const { + data: userData, + isLoading: isUserLoading, + error: userError, + } = useQuery({ + queryKey: ["auth-user"], + queryFn: async () => { + const { data, error } = await supabase.auth.getUser(); + if (error) throw error; + return data?.user; + }, + enabled: isAuthenticated, + subscribed: isFocused, + }); + const userId = userData?.id; const { data: profileData, @@ -54,7 +53,6 @@ export default function ProfileScreen() { subscribed: isFocused, }); - // Fetch user's foods for 'My Recipes' const { data: foodsData, isLoading: isFoodsLoading, @@ -69,7 +67,23 @@ export default function ProfileScreen() { subscribed: isFocused && activeTab === "My Recipes", }); - // Remove static foodItems, use foodsData for My Recipes + if (isUserLoading) { + return ( + + + + ); + } + + if (userError) { + return ( + + + {userError.message || "Failed to load user data."} + + + ); + } return (