1
+ import { useEffect , useState } from "react" ;
2
+ import { useSupabaseClient , useSession } from "@supabase/auth-helpers-react" ;
3
+
4
+ interface InventoryItem {
5
+ id : number ;
6
+ configuration : {
7
+ "missions unlocked" ?: string [ ] ;
8
+ [ key : string ] : any ; // Allow other properties in configuration
9
+ } ;
10
+ }
11
+
12
+ const UserMissions = ( ) => {
13
+ const supabase = useSupabaseClient ( ) ;
14
+ const session = useSession ( ) ;
15
+
16
+ const [ missions , setMissions ] = useState < string [ ] > ( [ ] ) ;
17
+ const [ loading , setLoading ] = useState ( true ) ;
18
+ const [ error , setError ] = useState < string | null > ( null ) ;
19
+
20
+ useEffect ( ( ) => {
21
+ if ( ! session ?. user ) return ;
22
+
23
+ const fetchUserMissions = async ( ) => {
24
+ setLoading ( true ) ;
25
+ setError ( null ) ;
26
+
27
+ try {
28
+ // Query inventory for items owned by the user and containing missions unlocked
29
+ const { data, error } = await supabase
30
+ . from ( "inventory" )
31
+ . select ( "id, configuration" )
32
+ . eq ( "owner" , session . user . id )
33
+ . not ( "configuration->missions unlocked" , "is" , null ) ; // Ensure "missions unlocked" exists
34
+
35
+ if ( error ) throw error ;
36
+
37
+ // Extract and deduplicate all "missions unlocked"
38
+ const unlockedMissions = data
39
+ ?. flatMap ( ( item : InventoryItem ) => item . configuration [ "missions unlocked" ] || [ ] )
40
+ . filter ( ( mission : string ) => mission ) ; // Filter out empty values
41
+
42
+ const uniqueMissions = Array . from ( new Set ( unlockedMissions ) ) ;
43
+
44
+ setMissions ( uniqueMissions ) ;
45
+ } catch ( err ) {
46
+ console . error ( "Error fetching user missions:" , err ) ;
47
+ setError ( "Failed to fetch missions. Please try again." ) ;
48
+ } finally {
49
+ setLoading ( false ) ;
50
+ }
51
+ } ;
52
+
53
+ fetchUserMissions ( ) ;
54
+ } , [ session ?. user , supabase ] ) ;
55
+
56
+ if ( ! session ?. user ) return < p className = "text-gray-400" > Please log in to see your missions.</ p > ;
57
+
58
+ if ( loading ) return < p className = "text-gray-400" > Loading missions...</ p > ;
59
+
60
+ if ( error ) return < p className = "text-red-500" > { error } </ p > ;
61
+
62
+ if ( missions . length === 0 ) {
63
+ return < p className = "text-gray-400" > No missions unlocked yet.</ p > ;
64
+ }
65
+
66
+ return (
67
+ < div className = "bg-gray-800 text-white rounded-lg p-6" >
68
+ < h1 className = "text-xl font-bold mb-4" > Missions Unlocked</ h1 >
69
+ < ul className = "list-disc pl-6" >
70
+ { missions . map ( ( mission , index ) => (
71
+ < li key = { index } className = "mb-2" >
72
+ { mission }
73
+ </ li >
74
+ ) ) }
75
+ </ ul >
76
+ </ div >
77
+ ) ;
78
+ } ;
79
+
80
+ export default UserMissions ;
0 commit comments