Files
rn-app/stores/tenantStore.ts
2025-11-06 16:37:01 +08:00

123 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* 租户状态管理
* 使用 Zustand + AsyncStorage 持久化
*/
import { create } from 'zustand';
import { useShallow } from 'zustand/react/shallow';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { STORAGE_KEYS } from '@/utils/storage';
import { tenantService } from '@/services/tenantService';
import { useEffect } from 'react';
/**
* 租户信息接口
*/
// export interface Tenant {
// id: string;
// username: string;
// email: string;
// avatar?: string;
// nickname?: string;
// phone?: string;
// createdAt?: string;
// }
/**
* 租户状态接口
*/
interface TenantState {
// 状态
tenantInfo: Record<string, any> | null;
// 操作
setTenantInfo: (data: Record<string, any>) => void;
requestTenantInfo: (data?: Record<string, any>) => Promise<any>;
}
/**
* 租户状态 Store
*/
const useTenantStore = create<TenantState>()((set, get) => ({
// 初始状态
tenantInfo: null,
// 设置租户信息(通用方法,包含持久化逻辑)
setTenantInfo: (data: any) => {
set({ tenantInfo: data });
// 手动持久化
// AsyncStorage.setItem(STORAGE_KEYS.TENANT_STORE, JSON.stringify({ tenantInfo: data }));
if (__DEV__) {
console.log('💾 Tenant info saved:', data);
}
},
// 获取租户信息(调用 API 并使用 setTenantInfo 保存)
requestTenantInfo: async () => {
try {
const params = {
domain_addr: 'https://51zhh5.notbug.org',
};
const { data } = await tenantService.getPlatformData(params);
// 调用 setTenantInfo 来保存数据,避免重复代码
get().setTenantInfo(data);
if (__DEV__) {
console.log('✅ Tenant info loaded:', data);
}
return Promise.resolve(data);
} catch (error) {
console.error('Failed to request tenant info:', error);
return Promise.reject(error);
}
},
}));
// 从 AsyncStorage 恢复状态的函数
export const restoreTenantState = async () => {
try {
const stored = await AsyncStorage.getItem(STORAGE_KEYS.TENANT_STORE);
if (stored) {
const state = JSON.parse(stored);
useTenantStore.setState(state);
if (__DEV__) {
console.log('✅ Tenant state restored from storage');
}
}
} catch (error) {
console.error('Failed to restore tenant state:', error);
}
};
/**
* 选择器 Hooks优化性能避免不必要的重渲染
*/
// 获取用户信息
export const useTenantInfo = () => useTenantStore((state) => state.tenantInfo);
// 获取租户状态
export const useTenantStates = () =>
useTenantStore(
useShallow((state) => ({
tenantInfo: state.tenantInfo,
tenantLoad: !!state.tenantInfo?.tid || !!state.tenantInfo?.create_time,
}))
);
// 获取租户操作方法
// 使用 useShallow 避免每次渲染都返回新对象
export const useTenantActions = () =>
useTenantStore(
useShallow((state) => ({
setTenantInfo: state.setTenantInfo,
requestTenantInfo: state.requestTenantInfo,
}))
);
export default useTenantStore;