ui/src/context/AppContext.tsx (view raw)
1import { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
2import type { User } from '../types/models';
3import { userService } from '../services/api';
4
5interface AppContextType {
6 user: User | null;
7 isLoading: boolean;
8 error: string | null;
9 updateUser: (profile: User) => Promise<void>;
10}
11
12const defaultProfile: User = {
13 name: 'User',
14 isFemale: false,
15 weight: 85,
16 height: 180,
17 birthDate: "01/01/1990",
18};
19
20const AppContext = createContext<AppContextType>({
21 user: defaultProfile,
22 isLoading: false,
23 error: null,
24 updateUser: async () => {},
25});
26
27export const useAppContext = () => useContext(AppContext);
28
29interface AppProviderProps {
30 children: ReactNode;
31}
32
33export const AppProvider = ({ children }: AppProviderProps) => {
34 const [user, setUser] = useState<User | null>(null);
35 const [isLoading, setIsLoading] = useState<boolean>(true);
36 const [error, setError] = useState<string | null>(null);
37
38 useEffect(() => {
39 const loadProfile = async () => {
40 try {
41 setIsLoading(true);
42 const profile = await userService.get(1);
43 setUser(profile);
44 setError(null);
45 } catch (err) {
46 console.error('Failed to load user profile:', err);
47 // For the single-user mode, create a default profile if none exists
48 setUser(defaultProfile);
49 setError('Could not load profile. Using default settings.');
50 } finally {
51 setIsLoading(false);
52 }
53 };
54
55 loadProfile();
56 }, []);
57
58 const updateUser = async (profile: User) => {
59 try {
60 setIsLoading(true);
61 const updatedProfile = await userService.update(1, profile);
62 setUser(updatedProfile);
63 setError(null);
64 } catch (err) {
65 console.error('Failed to update profile:', err);
66 setError('Failed to update profile. Please try again.');
67 throw err;
68 } finally {
69 setIsLoading(false);
70 }
71 };
72
73 return (
74 <AppContext.Provider value={{ user, isLoading, error, updateUser }}>
75 {children}
76 </AppContext.Provider>
77 );
78};