feat;提交管理端和城市合伙人端
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react';
|
||||
import { clearAuth, isLoggedIn, request } from '../lib/api';
|
||||
|
||||
export type PartnerAccount = {
|
||||
id: string;
|
||||
name: string;
|
||||
phone: string;
|
||||
isPrimary?: boolean;
|
||||
companyName?: string;
|
||||
hasWechat?: boolean;
|
||||
};
|
||||
|
||||
type PartnerSessionValue = {
|
||||
account: PartnerAccount | null;
|
||||
loading: boolean;
|
||||
loggedIn: boolean;
|
||||
refresh: () => Promise<void>;
|
||||
logout: () => void;
|
||||
};
|
||||
|
||||
const PartnerSessionContext = createContext<PartnerSessionValue | null>(null);
|
||||
|
||||
export function PartnerSessionProvider({ children }: { children: ReactNode }) {
|
||||
const [account, setAccount] = useState<PartnerAccount | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
if (!isLoggedIn()) {
|
||||
setAccount(null);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const data = await request<PartnerAccount>('PARTNER_H5', '/partner/me');
|
||||
setAccount(data);
|
||||
} catch {
|
||||
setAccount(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
clearAuth();
|
||||
setAccount(null);
|
||||
window.location.href = '/login';
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return (
|
||||
<PartnerSessionContext.Provider
|
||||
value={{ account, loading, loggedIn: isLoggedIn(), refresh, logout }}
|
||||
>
|
||||
{children}
|
||||
</PartnerSessionContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function usePartnerSession(): PartnerSessionValue {
|
||||
const ctx = useContext(PartnerSessionContext);
|
||||
if (!ctx) throw new Error('usePartnerSession 必须在 PartnerSessionProvider 内使用');
|
||||
return ctx;
|
||||
}
|
||||
Reference in New Issue
Block a user