mirror of
https://github.com/tinyhumansai/openhuman.git
synced 2026-07-30 15:03:57 +00:00
6.7 KiB
6.7 KiB
description, icon
| description | icon |
|---|---|
| Redux Toolkit + Redux-Persist patterns used in the React app. | database |
State Management
The application uses Redux Toolkit with Redux-Persist for robust state management.
Store Configuration
File: store/index.ts
// Combines all slices with persistence
const persistConfig = {
key: 'root',
storage,
whitelist: ['auth', 'telegram'], // Persisted slices
};
Redux State Structure
RootState = {
auth: {
token: string | null, // JWT (persisted)
isOnboardedByUser: Record<string, boolean>, // Per-user flag (persisted)
},
socket: {
byUser: Record<
string,
{
// Per user ID
status: 'connecting' | 'connected' | 'disconnected';
socketId: string | null;
}
>,
},
user: { profile: User | null, loading: boolean, error: string | null },
telegram: {
byUser: Record<string, TelegramState>, // Per Telegram user (persisted)
},
};
Slices
Auth Slice (store/authSlice.ts)
Manages JWT token and per-user onboarding status.
State:
interface AuthState {
token: string | null;
isOnboardedByUser: Record<string, boolean>;
}
Actions:
setToken(token: string)- Store JWT after loginclearToken()- Remove token on logoutsetOnboarded({ userId, isOnboarded })- Mark user as onboarded
Selectors (store/authSelectors.ts):
selectToken- Get current JWTselectIsOnboarded(userId)- Check if user completed onboarding
Socket Slice (store/socketSlice.ts)
Tracks Socket.io connection status per user.
State:
interface SocketState {
byUser: Record<
string,
{ status: 'connecting' | 'connected' | 'disconnected'; socketId: string | null }
>;
}
Actions:
setSocketStatus({ userId, status })- Update connection statussetSocketId({ userId, socketId })- Store socket IDclearSocketState(userId)- Clear user's socket state
Selectors (store/socketSelectors.ts):
selectSocketStatus(userId)- Get connection statusselectIsSocketConnected(userId)- Boolean connected check
User Slice (store/userSlice.ts)
Stores user profile data.
State:
interface UserState {
profile: User | null;
loading: boolean;
error: string | null;
}
Actions:
setUser(user)- Store user profilesetUserLoading(loading)- Set loading statesetUserError(error)- Set error stateclearUser()- Clear profile on logout
Telegram Slice (store/telegram/)
Complex nested state management for Telegram integration.
Files:
index.ts- Slice exports (actions, thunks)types.ts- Entity and state interfacesreducers.ts- Synchronous reducersextraReducers.ts- Async thunk handlersthunks.ts- Async operations
State Structure:
telegram.byUser[telegramUserId] = {
connectionStatus: "disconnected" | "connecting" | "connected" | "error",
authStatus: "not_authenticated" | "authenticating" | "authenticated" | "error",
currentUser: TelegramUser | null,
sessionString: string | null, // Stored here, NOT localStorage
chats: Record<string, TelegramChat>,
chatsOrder: string[],
messages: Record<chatId, Record<msgId, TelegramMessage>>,
threads: Record<chatId, TelegramThread[]>
}
Reducers:
setCurrentUser- Store authenticated Telegram usersetSessionString- Store MTProto session (for persistence)setConnectionStatus- Update connection statesetAuthStatus- Update authentication stateaddChat/updateChat- Manage chat listaddMessage/updateMessage- Manage message historysetThreads- Store thread data
Thunks (store/telegram/thunks.ts):
initializeTelegram(userId)- Initialize MTProto clientconnectTelegram(userId)- Establish Telegram connectionfetchChats(userId)- Load chat listfetchMessages({ userId, chatId })- Load message historydisconnectTelegram(userId)- Clean disconnect
Selectors (store/telegramSelectors.ts):
selectTelegramState(userId)- Get full Telegram stateselectTelegramConnectionStatus(userId)- Get connection statusselectTelegramAuthStatus(userId)- Get auth statusselectTelegramChats(userId)- Get chat listselectTelegramMessages(userId, chatId)- Get messages for chat
Typed Hooks
File: store/hooks.ts
// Use these instead of plain useDispatch/useSelector
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
Persistence Configuration
What's Persisted
auth.token- JWT for authenticationauth.isOnboardedByUser- Per-user onboarding statustelegram.byUser- Telegram state (sessions, chats, etc.)
What's NOT Persisted
socket- Connection state (reconnects on app start)user.loading/user.error- Transient UI states- Telegram loading/error states
Storage Backend
Redux-Persist uses localStorage adapter by default. This is the ONLY acceptable use of localStorage in the application.
Usage Examples
Reading State
import { useAppSelector } from '../store/hooks';
function MyComponent() {
const token = useAppSelector(state => state.auth.token);
const isConnected = useAppSelector(state => state.socket.byUser[userId]?.status === 'connected');
const chats = useAppSelector(state => state.telegram.byUser[userId]?.chats);
}
Dispatching Actions
import { clearToken, setToken } from '../store/authSlice';
import { useAppDispatch } from '../store/hooks';
import { initializeTelegram } from '../store/telegram/thunks';
function MyComponent() {
const dispatch = useAppDispatch();
// Sync action
const handleLogin = (token: string) => {
dispatch(setToken(token));
};
// Async thunk
const handleConnect = async () => {
await dispatch(initializeTelegram(userId)).unwrap();
};
}
Using Selectors
import { selectIsOnboarded } from '../store/authSelectors';
import { useAppSelector } from '../store/hooks';
import { selectTelegramConnectionStatus } from '../store/telegramSelectors';
function MyComponent({ userId }) {
const isOnboarded = useAppSelector(state => selectIsOnboarded(state, userId));
const connectionStatus = useAppSelector(state => selectTelegramConnectionStatus(state, userId));
}
Best Practices
- Always use typed hooks -
useAppDispatchanduseAppSelector - Use selectors for derived state - Memoized and testable
- Keep thunks in separate files - Better organization
- Per-user state scoping - Key state by user ID
- Avoid localStorage - Use Redux-Persist instead
Previous: Architecture Overview | Next: Services Layer