initial commit
This commit is contained in:
71
src/context/AppContext.tsx
Normal file
71
src/context/AppContext.tsx
Normal file
@@ -0,0 +1,71 @@
|
||||
// src/context/AppContext.tsx
|
||||
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
||||
import { api } from '../api';
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
phone_number: string;
|
||||
first_name: string;
|
||||
last_name: string;
|
||||
}
|
||||
|
||||
interface Workspace {
|
||||
id: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface AppContextType {
|
||||
user: User | null;
|
||||
workspaces: Workspace[];
|
||||
activeWorkspace: Workspace | null;
|
||||
setActiveWorkspace: (ws: Workspace) => void;
|
||||
fetchInitialData: () => Promise<void>;
|
||||
}
|
||||
|
||||
const AppContext = createContext<AppContextType | null>(null);
|
||||
|
||||
export const AppProvider = ({ children }: { children: ReactNode }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [workspaces, setWorkspaces] = useState<Workspace[]>([]);
|
||||
const [activeWorkspace, setActiveWorkspace] = useState<Workspace | null>(null);
|
||||
|
||||
const fetchInitialData = async () => {
|
||||
try {
|
||||
const [userRes, wsRes] = await Promise.all([
|
||||
api.get('/api/users/me/'),
|
||||
api.get('/api/workspaces/')
|
||||
]);
|
||||
|
||||
setUser(userRes.data);
|
||||
setWorkspaces(wsRes.data.results || wsRes.data);
|
||||
|
||||
const savedWsId = localStorage.getItem('active_workspace');
|
||||
const targetWs = wsRes.data.find((w: Workspace) => w.id === savedWsId) || wsRes.data[0];
|
||||
|
||||
if (targetWs) {
|
||||
setActiveWorkspace(targetWs);
|
||||
localStorage.setItem('active_workspace', targetWs.id);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (localStorage.getItem('accessToken')) {
|
||||
fetchInitialData();
|
||||
}
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={{ user, workspaces, activeWorkspace, setActiveWorkspace, fetchInitialData }}>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useAppContext = () => {
|
||||
const context = useContext(AppContext);
|
||||
if (!context) throw new Error('useAppContext must be used within AppProvider');
|
||||
return context;
|
||||
};
|
||||
Reference in New Issue
Block a user