cryogenic22 commited on
Commit
76d6db7
·
verified ·
1 Parent(s): 03f730d

Create frontend/src/contexts/UserContext.tsx

Browse files
frontend/src/contexts/UserContext.tsx ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import React, { createContext, useContext, useState } from 'react';
2
+
3
+ interface UserState {
4
+ isAuthenticated: boolean;
5
+ username: string | null;
6
+ progress: {
7
+ completedModules: string[];
8
+ achievements: Array<{
9
+ name: string;
10
+ date: string;
11
+ description: string;
12
+ }>;
13
+ learningStreak: number;
14
+ };
15
+ }
16
+
17
+ interface UserContextType {
18
+ user: UserState;
19
+ login: (username: string) => void;
20
+ logout: () => void;
21
+ updateProgress: (moduleId: string) => void;
22
+ }
23
+
24
+ const defaultUserState: UserState = {
25
+ isAuthenticated: false,
26
+ username: null,
27
+ progress: {
28
+ completedModules: [],
29
+ achievements: [],
30
+ learningStreak: 0
31
+ }
32
+ };
33
+
34
+ const UserContext = createContext<UserContextType | undefined>(undefined);
35
+
36
+ export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
37
+ const [user, setUser] = useState<UserState>(defaultUserState);
38
+
39
+ const login = (username: string) => {
40
+ setUser({
41
+ isAuthenticated: true,
42
+ username,
43
+ progress: {
44
+ ...defaultUserState.progress
45
+ }
46
+ });
47
+ };
48
+
49
+ const logout = () => {
50
+ setUser(defaultUserState);
51
+ };
52
+
53
+ const updateProgress = (moduleId: string) => {
54
+ setUser(prev => ({
55
+ ...prev,
56
+ progress: {
57
+ ...prev.progress,
58
+ completedModules: [...prev.progress.completedModules, moduleId]
59
+ }
60
+ }));
61
+ };
62
+
63
+ return (
64
+ <UserContext.Provider value={{ user, login, logout, updateProgress }}>
65
+ {children}
66
+ </UserContext.Provider>
67
+ );
68
+ };
69
+
70
+ export const useUser = () => {
71
+ const context = useContext(UserContext);
72
+ if (context === undefined) {
73
+ throw new Error('useUser must be used within a UserProvider');
74
+ }
75
+ return context;
76
+ };