Files
ok_r/components/user-context.tsx
2026-01-25 21:55:29 +08:00

86 lines
2.3 KiB
TypeScript

'use client';
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
import type { User } from '@/types/database';
interface UserContextType {
currentUser: User | null;
users: User[];
isLoading: boolean;
isInitialized: boolean;
setCurrentUserId: (id: string) => void;
refreshUsers: () => Promise<void>;
}
const UserContext = createContext<UserContextType | undefined>(undefined);
export function UserProvider({ children }: { children: ReactNode }) {
const [currentUser, setCurrentUser] = useState<User | null>(null);
const [users, setUsers] = useState<User[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isInitialized, setIsInitialized] = useState(false);
const refreshUsers = useCallback(async () => {
try {
const res = await fetch('/api/users');
if (res.ok) {
const data = await res.json();
setUsers(data);
return data;
}
} catch (error) {
console.error('Failed to fetch users:', error);
}
return [];
}, []);
useEffect(() => {
async function init() {
setIsLoading(true);
const fetchedUsers = await refreshUsers();
if (fetchedUsers.length > 0) {
const storedId = localStorage.getItem('currentUserId');
const foundUser = storedId
? fetchedUsers.find((u: User) => u.id === storedId)
: null;
if (foundUser) {
setCurrentUser(foundUser);
} else {
const owner = fetchedUsers.find((u: User) => u.role === 'owner') || fetchedUsers[0];
setCurrentUser(owner);
localStorage.setItem('currentUserId', owner.id);
}
setIsInitialized(true);
}
setIsLoading(false);
}
init();
}, [refreshUsers]);
const setCurrentUserId = useCallback((id: string) => {
const user = users.find(u => u.id === id);
if (user) {
setCurrentUser(user);
localStorage.setItem('currentUserId', id);
}
}, [users]);
return (
<UserContext.Provider value={{ currentUser, users, isLoading, isInitialized, setCurrentUserId, refreshUsers }}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (context === undefined) {
throw new Error('useUser must be used within a UserProvider');
}
return context;
}